如何在另一个函数中引用自定义 UITableView 单元格 (Swift)

How to reference custom UITableView cell inside another function (Swift)

我正在尝试实现类似于 Apple 的提醒应用程序的功能,其中一个 tableview 包含所有提醒,最后的 + 按钮添加一个新的 object。

我的 object 保存在一个名为 tempActions 的数组中,它是 tableView 的数据源。

按 'Add Action' 将新的 object 附加到标题为 "Empty Cell" 的数组。

标题是 UITextView 用户可以编辑,但我不知道该怎么做:

如何从该特定单元格的 UITextView 中获取文本,将其附加到正确索引处的数组(索引对应于 indexPath.row),然后在 cell.label?

中显示

我想过使用 textViewDidEndEditing 方法,但我不知道如何从 cellForRowAt 方法中引用正确的单元格。

有谁能帮助澄清这一点,还是我的处理方式有误?

这是整个 class 的代码:

class Step3: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextViewDelegate {

// Outlets
@IBOutlet weak var sectionText: UILabel!
@IBOutlet weak var sectionHeader: UILabel!
@IBOutlet weak var teableViewHeight: NSLayoutConstraint!
@IBOutlet weak var tableview: UITableView!

@IBAction func addAction(_ sender: Any) {

    tempActions.append(Action(title: "Empty Cell", completed: false))

    tableview.reloadData()
    tableview.layoutIfNeeded()
    teableViewHeight.constant = tableview.contentSize.height

    print(tempActions)
}

@IBAction func nextAction(_ sender: Any) {

    let newGoal = Goal(
        title: tempTitle,
        description: tempDescription,
        duration: tempDuration,
        actions: nil,
        completed: false
    )

    newGoal.save()

    performSegue(withIdentifier: "ToHome", sender: nil)
}


func textViewDidEndEditing(_ textView: UITextView) {
}


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return tempActions.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "ActionCell", for: indexPath) as! ActionCell

    cell.label.text = tempActions[indexPath.row].title
    cell.label.textContainerInset = UIEdgeInsets(top: 12, left: 0, bottom: 12, right: 0);
    cell.label.delegate = self

    return cell
}

override func viewDidLoad() {
    super.viewDidLoad()
    tableview.estimatedRowHeight = 40
    tableview.rowHeight = UITableView.automaticDimension
}

}

提前致谢

如果我理解的话 -- textView 在一个单元格中,而您想在 textViewDidEndEditing 中找到该单元格。如果文本域的父视图是单元格,你可以这样做:

func textViewDidEndEditing(_ textView: UITextView) {
    if let cell = textView.superview as? ActionCell, 
         let indexPath = tableView.indexPath(for: cell) {
      // Now you have the indexPath of the cell
      // update tempActions

           // YOUR CODE HERE

      // Then reloadRows
      tableView.reloadRows(at: [indexPath]), with: .automatic)
    }
}

您可以做的另一件事是使 tempAction 的类型具有唯一 ID,然后将其存储在 ActionCell 中——当您想要查找索引时,在 tempActions 数组中查找 ID 以找到其索引.