【问题标题】:How do I get the row number of the cell where the UITextView was edited?如何获取编辑 UITextView 的单元格的行号?
【发布时间】:2018-12-26 21:39:40
【问题描述】:
  • 我在 UITableView 的每个单元格内都有一个 UITextView
  • 我正在使用 Core Data 来保存在 UITextView 中输入的数据
  • 一旦用户完成编辑,我想保存在 UITextView 中输入的文本
  • 我已将 UITextViewDelegate 添加到我的 TableViewCell 类中
  • 我正在使用 Notifications 将新文本发布到 TableViewController

我能够将新文本添加到 TableViewController,但我不知道如何获取包含输入文本的 textview 的单元格的行号。我需要知道行号(或该行中的对象)来更新正确的 NSManagedObject。

我尝试过的:

  • 我正在考虑使用标签,但由于我需要不断添加和删除行,这不是最好的方法

  • 我已尝试使用 DidSelectedRowAtIndexPath,但在 用户点击 UITextView(UITextView 最多覆盖一个单元格的 80%)

在 TableViewCell 类中,我有:

    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)")   
    }

不要犹豫,询问更多详情。 我会很感激我能得到的每一点帮助!

【问题讨论】:

    标签: swift uitableview uitextview


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

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

    【讨论】:

      【解决方案2】:

      我希望您可以在 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`
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2017-12-23
        • 1970-01-01
        • 2017-12-10
        • 2010-12-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多