Swift - 如何在按下不同自定义单元格中的按钮时获取自定义单元格标签的值?

Swift - How to get the value of a custom cell label when pressing a button in a different custom cell?

这个问题有点碰壁。

我有一个动态原型的TableView。 TableView 有 2 个部分。

第 1 部分从 xib 文件加载自定义 TableViewCell。单元格包含步进器和标签:

class quantityTableViewCell: UITableViewCell {

 @IBOutlet weak var quantityLabel: UILabel!


 @IBAction func quantityStepper(_ sender: UIStepper) {
    quantityLabel.text = String(Int(sender.value))
 }

}

第 2 部分加载另一个自定义 TableViewCell,其中仅包含一个按钮:

class addToBasketTableViewCell: UITableViewCell {

 @IBOutlet weak var submitButton: UIButton!

}

现在,在我的 TableView class 中,两个单元格都被加载到各自的部分中,我想在单击第二部分中的按钮时捕获第一部分中 'quantityLabel' 的当前值部分并将结果打印到控制台。

例如,如果我将值步进到 5,当我点击 'submitButton' 时它会打印“5”。

我有点不确定该怎么做,任何指导都会很好。下面是正在加载的单元格的副本:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let item: ItemPreBasketModel = cellItems[indexPath.row] as! ItemPreBasketModel

    if indexPath.section == 0 {

        let quantityCell = Bundle.main.loadNibNamed("quantityTableViewCell", owner: self, options: nil)?.first as! quantityTableViewCell
        return quantityCell

        } else if indexPath.section == 1 {

        let addToBasketCell = Bundle.main.loadNibNamed("addToBasketTableViewCell", owner: self, options: nil)?.first as! addToBasketTableViewCell
        return addToBasketCell

    }
}

您永远不应依赖单元格中的值,因为当用户滚动 table 视图时,单元格可能会出现和消失。

相反,您应该将步进器的值存储在模型中,当用户点击按钮时,从模型(而不是从任何单元格)中读取值。

所以:

  • 当调用 quantityStepper 时,更新标签并通知某些委托(例如托管视图控制器)值已更改。意识到:
    1. 您应该直接从quantityTableViewCell
    2. 中更新模型
    3. 相反,您应该向某个委托(实现此协议)发送一条消息(=您自己的协议)以通知它该值已更改为某个值
    4. 委托(可能是你的视图控制器)将把这个值存储在某处
  • addToBasketTableViewCell被调用时,你也应该通知委托人这件事。委托(您的视图控制器)然后将使用他在 3 中获得的值并执行任何必须完成的操作。

通过这种方法,细胞彼此解耦。单元格重用没有任何问题,您可以正确初始化单元格,因为值始终存储在模型中,而单元格仅显示它。更新始终反映到模型中。

应该是这样的:

let path = IndexPath(item: 0, section: 0)
let cell = table.cellForRow(at: path) as? quantityTableViewCell
print(cell?.quantityLabel.text)

将 "table" 替换为您的 table 对象。