如何获取编辑 UITextView 的单元格的行号?

How do I get the row number of the cell where the UITextView was edited?

I am able to get the new text to the TableViewController but I don't know how to get the row number of the cell that contained the textview wherein the text was typed. I need to know the row number (or the object in that row) to update the correct NSManagedObject.

我尝试过的:

在 TableViewCell class 中,我有:

    func textViewDidEndEditing(_ textView: UITextView) {

    // Post notification

    let userInfo = [ "text" : textView.text]

    NotificationCenter.default.post(
    name: UITextView.textDidEndEditingNotification, 
    object: nil, 
    userInfo: userInfo as [AnyHashable : Any])
}

在 TableViewController 中,我有:

    //Subscribe
    NotificationCenter.default.addObserver(self, 
    selector: #selector(textEditingEnded(notification:)),
    name: UITextView.textDidEndEditingNotification, 
    object: nil)


    @objc func textEditingEnded(notification:Notification) {

        guard let text = notification.userInfo?["text"] as? String else {return}
        print ("text: \(text)")   
    }

请随时询问更多详情。 我会很感激我能得到的每一点帮助!

  • 在 table 视图单元格中创建 NSManagedObject 类型的 属性。
  • 在 Interface Builder 中,将文本视图的 delegate 连接到单元格。
  • 在控制器中将 cellForRowAt 中适当的数据源项传递给单元格。
  • 删除观察者而不是发布通知,直接更改 NSManagedObject 实例中的属性并保存上下文。

由于 NSManagedObject 实例是引用类型,因此更改将持续存在。

我希望您可以在 UITableViewCell 子类中为某些项目设置变量

var item: Item?

然后在cellForRowAt中为特定的单元格设置特定的item

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = ...
    ...
    cell.item = array[indexPath.row]
    ...
}

现在您可以将 UITextViewDelegate 实现到您的单元格子类,并且您可以使用方法 textViewDidEndEditing 在用户完成输入时进行处理

class YourCell: UITableViewCell {
    ...
    var item: Item?
    ...
    override func awakeFromNib() {
        yourTextView.delegate = self
    }
}

extension YourCell: UITextViewDelegate {
    func textViewDidEndEditing(_ textView: UITextView) {
         ... // here save text and here you can use variable `item`
    }
}