I use UserDefault to stored an image that I have in TableView cell, I would like to know how can stored what is in the cell, when the button is pressed
Thank you so much
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var imageArray = [UIImage(named: "image1"), UIImage(named: "image2"),
UIImage(named: "image3"), UIImage(named: "image4"),
UIImage(named: "image5"), UIImage(named: "image6")]
var userDefault = UserDefaults.standard
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func imageRoll(_ sender: UIBarButtonItem) {
_ = imageArray.shuffle()
tableView.reloadData()
}
@IBAction func addImage(_ sender: UIBarButtonItem) {
imageArray.insert(UIImage(named: "image1"), at: 0)
tableView.insertRows(at: [IndexPath(row: 0, section: 0)], with: .automatic)
}
@IBAction func saveConfig(_ sender: UIBarButtonItem) {
}
func saveData(){
}
}
extension ViewController: UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return imageArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: “ImageCell", for: indexPath) as! ImageTableViewCell
let images = imageArray[indexPath.row]
cell.imageCell.image = images
return cell
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
imageArray.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .automatic)
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 40
}
}
Firstly declare tableview cell globally:-
var cell : ImageTableViewCell?
Create image array to save in user default:-
var saverImageArr = [UIImage?]()
Now when button is pressed:-
@IBAction func imageRoll(_ sender: UIBarButtonItem) {
for image in 0..<imageArray.count {
if saverImageArr.count > 0
{
saverImageArr.removeAll()
}
saverImageArr.append(cell.imageCell.image)
}
UserDefaults.standard.set(saverImageArr, forKey: "imageArray")
UserDefaults.standard.synchronize()
tableView.reloadData()
}
Now to get that array from user default:-
if let imageArrfromUserdefault = UserDefaults.standard.array(forKey: "imageArray")
{
print(imageArrfromUserdefault)
}
else
{
print("empty array")
}
Thank you.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.