簡體   English   中英

按下按鈕時,用戶默認在 TableView 中保存單元格

[英]UserDefault save cell in TableView when button is pressed

我使用 UserDefault 來存儲我在 TableView 單元格中的圖像,我想知道當按下按鈕時如何存儲單元格中的內容

太感謝了

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
}

}

首先全局聲明tableview單元格:-

var cell : ImageTableViewCell?

創建圖像數組以保存在用戶默認值中:-

var saverImageArr = [UIImage?]()

現在按下按鈕時:-

@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()
}

現在從用戶默認獲取該數組:-

if let imageArrfromUserdefault = UserDefaults.standard.array(forKey: "imageArray")
   {
        print(imageArrfromUserdefault)
   }
   else
   {
        print("empty array")
   }

謝謝你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM