首页 > 解决方案 > 快速,从具有 CustomCells 的 tableViewCells 中检索更改的数据

问题描述

这个问题在很多地方都被问过几次,但理解和解决它非常困难。

我的问题不同,我在研究了 5 个多小时后才提出这个问题。

我有一个 tableView,其中有 3 种不同类型的 CustomCell。

我的自定义单元格有 3 个东西,2 个通用标签和一个 TextField。第三项(步进器、按钮、开关)

我已经动态放置了 10 个单元格调用

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

我理想中想做的事->

当我的用户更改单元格上的数据时,我想获取所有“更新”的数据,以便在单击“保存”时将其保存到我的数据库中。

我尝试使用

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

并使用断点,显然当我触摸单元格时会触发代码块。不幸的是,触摸意味着从字面上触摸列表条目主体。

如果我使用自定义单元格中的 UI 项(步进器/开关),则不会触发此代码部分。

我见过使用标签和委托的解决方案,但由于我是 iOS 新手,我不确定如何实施或继续。我正在使用 Angela 的 Udemy iOS 课程自学。

自定义单元格 在此处输入图像描述

整个屏幕,当用户更改它们时,我喜欢获取文本字段值 动态填充的 tableview 的屏幕截图

标签: iosswiftuitableviewtableviewcustom-cell

解决方案


(已测试)您好,我用来解决此问题的一种方法是将处理程序函数添加到您已初始化 tableView 的子类之外。

    //.... This is your cellForRowAt tableView function..
    let cell = self.tableView.dequeueReusableCell(withIdentifier: cellId) as! cellSubclass
    cell.stepperButton.addTarget(self, action: #selector(handleStep(_:)), for: .valueChanged)
    return cell
}

@objc func handleStep(_ sender: UIStepper) {
    print(sender.value)
    let indexPath : IndexPath = IndexPath(item: 0, section: 0) 
    // Put the correct item # to locate where you have the stepper,
    // Then create a separate function doing the same thing, but with the item 
    // number of the next cell where you get the value from the switch
    let cell = tableView.cellForRow(at: indexPath) as! cellSubclass
    cell.textField.text = "\(Int(sender.value))"
}

您正在通过创建单元格的函数内部的 addTarget 方法连接 UIStepper。

这是我的结果图片:在此处输入图像描述

提示:添加stepper.minimumValue = 0 当值 == 0 时,这会禁用 [ - ] 按钮。


推荐阅读