简体   繁体   English

保存来自uicollectionview单元更新的数据

[英]Saving data from updates of a uicollectionview cell

I have a collectionview generated from an Array of custom objects where each cell represent a counter with a value that can be updated with buttons "+" and "-". 我有一个自定义对象数组生成的collectionview,其中每个单元格代表一个计数器,该计数器的值可以通过按钮“ +”和“-”进行更新。

When I update this value with the buttons, it changes visually, but it's not saved to the array, so when I restarted my app, I have the older amount, the one before i do changes with the buttons 当我使用按钮更新此值时,它会发生外观变化,但不会保存到数组中,因此,当我重新启动应用程序时,我使用的是较旧的金额,之前我使用按钮进行了更改

var data: [CounterModel] = []

this is my array in my ViewController.swift 这是我的ViewController.swift中的数组

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CounterCell", for: indexPath) as! CounterCell
    cell.configure(with: data[indexPath.row])

    return cell
  }

this is where I configure my cell 这是我配置单元格的地方

 public func configure(with model: CounterModel) {
    nameLabel.text = model.name
    amountLabel.text = String(model.amount)
  }

  @IBAction func lessBtnTapped(_ sender: Any) {
    newAmount = Int(amountLabel.text!)

    if (newAmount == 0) {
      amountLabel.text = "\(newAmount!)"
    } else {
      amountLabel.text = "\(newAmount! - 1)"
    }
  }


  @IBAction func moreBtnTapped(_ sender: Any) {
    newAmount = Int(amountLabel.text!)

    amountLabel.text = "\(newAmount! + 1)"
  }

this is where I configure my cell and perform changes of the value (in CounterCell.swift) 这是我配置单元格并更改值的地方(在CounterCell.swift中)

struct CounterModel: Codable {
  var name: String
  var amount: Int
}

this is my CounterModel 这是我的CounterModel

EDIT (with missing informations) 编辑 (缺少信息)

I encode my counters in Json and save it in userdefaults : 我将计数器编码为Json并将其保存在userdefaults中:

func saveUserDefaults(counters: [CounterModel]) {
  let defaults = UserDefaults.standard

  let jsonEncoder = JSONEncoder()
  let jsonData = try? jsonEncoder.encode(counters)

  defaults.set(jsonData, forKey: "savedCounters")
}

func loadUserDefaults() -> [CounterModel] {
  let defaults = UserDefaults.standard
  var savedCounters: [CounterModel] = []

  guard let jsonData = defaults.object(forKey: "savedCounters") as? Data else { return savedCounters}

  let jsonDecoder = JSONDecoder()
  savedCounters = try! jsonDecoder.decode([CounterModel].self, from: jsonData)

  return savedCounters

I update my Userdefaults in an AlertAction when I create a new counter 创建新计数器时,我会在AlertAction中更新Userdefaults

let newCounter: CounterModel = CounterModel(name: self.newLabelValue!, amount: self.newAmountValue!)

      self.data.append(newCounter)
      saveUserDefaults(counters: self.data)

      self.data = loadUserDefaults()

      self.collectionView.reloadData()

You have to update your model. 您必须更新模型。 Transfer the tap to the view controller using a closure and do you logic there. 使用闭包将分路器转移到视图控制器,然后在此处进行逻辑处理。 A quick solution could be: 一个快速的解决方案可能是:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CounterCell", for: indexPath) as! CounterCell
    cell.configure(with: data[indexPath.row]) { newValue in
        self.data[indexPath.row].amount = newValue
        self.saveUserDefaults(counters: self.data)
    }

    return cell
}

The cell class: 单元格类别:

private var valueDidChange: ((Int) -> Void)?

public func configure(with model: CounterModel, valueDidChange: @escaping (Int) -> Void) {
    nameLabel.text = model.name
    amountLabel.text = String(model.amount)
    self.valueDidChange = valueDidChange
}

@IBAction func lessBtnTapped(_ sender: Any) {
    newAmount = Int(amountLabel.text!)

    if (newAmount == 0) {
      amountLabel.text = "\(newAmount!)"
    } else {
      amountLabel.text = "\(newAmount! - 1)"
    }
    valueDidChange?(newAmount)
}


@IBAction func moreBtnTapped(_ sender: Any) {
    newAmount = Int(amountLabel.text!)

    amountLabel.text = "\(newAmount! + 1)"
    valueDidChange?(newAmount)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从选定的UICollectionView单元格获取数据? - How to get data from a selected UICollectionView cell? 保存重新排序的uicollectionview单元无法正常工作 - Saving reordered uicollectionview cell not working without error 如何从UICollectionView的外部数据源获取单元格标题 - How to get Cell title from external data source for UICollectionView 如何将数据从ViewController传递到相应的UICollectionView单元格? - How to pass data from a viewcontroller to a corresponding UICollectionView cell? 来自UICollectionView Cell的Swift 3 Segue - Swift 3 Segue from UICollectionView Cell 从照片中获取数据源的UICollectionView-包含大量照片的缓慢更新 - UICollectionView with data source fetched from Photos - slow updates with big amount of photos 保存对象Parse.com时UiCollectionView不选择Corret Cell - UiCollectionView not select corret Cell when saving object Parse.com 由UICollectionView调用以显示单元格时,数据未从Core Data完全加载 - Data not fully loaded from Core Data when being called by UICollectionView to display cell UICollectionView在迅速滚动2时更改单元格数据 - UICollectionView change cell data when scrolled in swift 2 如何从外部UICollectionView更改UICollectionView单元格背景颜色 - How To Change UICollectionView Cell Background Colour From Outside UICollectionView
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM