ios - 当 TextViewCell 在屏幕上不可见时如何成为 TableViewCell 中的 FirstResponder TextField

标签 ios swift

使用 Xcode 9.2 版 Swift 开发 iOS 应用程序。

点击 RightNavigationButtonAdd 后,我想在 TableView 的开头插入一个 TableViewCell,并在其中聚焦(成为 FirstResponder)TextField。

当插入的TableViewCell可见时,正常工作。但是,当插入的 TableViewCell 不可见时,由于 cellForRow 返回 nil 而发生错误。

你能告诉我怎么做吗?

RightNavigationButtonAdd Action 代码

@objc func RightNavigationButtonAdd(_ sender: UIBarButtonItem) {

    // array is ["aaa", "bbb", "ccc", "ddd", ...]
    array.insert("", at: 0)
    // ttableView is @IBOutlet var ttableView: UITableView!
    // it is set to "No selection during editing"
    ttableView.insertRows(at: [IndexPath(row:0, section:0)], with: .top)

    // when inserted cell is invisible, error occured:
    // "Fatal error: Unexpectedly found nil while unwrapping an Optional value"
    let cell = ttableView.cellForRow(at: IndexPath(row:0, section:0)) as! TableViewCell

    cell.textField.becomeFirstResponder()
    cell.textField.placeholder = "input anything ..."
    ttableView.scrollToRow(at: IndexPath(row:0, section:0), at: .top, animated: true)
}

Screenshot when inserted cell is visible -> it works normally

Screenshot when inserted cell is invisible -> error occured

最佳答案

你的代码几乎没问题,但你崩溃了,因为那个单元格超出了范围,所以首先你必须滚动到开头(使其可见),然后你将能够在这样的 IndexPath(行:0,部分:0)。您可以查看 cellForRow 的文档:

An object representing a cell of the table, or nil if the cell is not visible or indexPath is out of range.

这里是解决方案:

@objc func RightNavigationButtonAdd(_ sender: UIBarButtonItem) {
   array.insert("", at: 0)
   ttableView.insertRows(at: [IndexPath(row:0, section:0)], with: .top)

   UIView.animate(withDuration: 0.3, animations: {
        self.ttableView.scrollToRow(at: IndexPath(row:0, section:0), at: .top, animated: true)
    }) { (success) in
        let cell = self.ttableView.cellForRow(at: IndexPath(row:0, section:0)) as! TableViewCell
        cell.textField.becomeFirstResponder()
        cell.textField.placeholder = "input anything ..."
    }
}

关于ios - 当 TextViewCell 在屏幕上不可见时如何成为 TableViewCell 中的 FirstResponder TextField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48125738/

相关文章:

ios - 更改后我的框架高度没有更新

IOS 推送通知在临时模式下不起作用

ios - 如何通过从 Swift 中的 UIScrollView 继承它来制作垂直的 UITextView?

ios - 谷歌地图自动完成

iOS 13.3.1 错误 "dyld: Library not loaded:...Reason: no suitable image found. Did find:..."应用程序崩溃 [swift][xcode]

ios - 只允许 2 个用户从公共(public)类读取一个对象

ios - 将 iOS-Charts Float 设置为整数 YAxis

ios - 关闭我添加的 View 后 UITableView 单元格消失

ios - 如何将 VoiceOver 辅助功能添加到应用程序的图标角标(Badge)编号?

ios - Swift 中的 MagicalRecord createEntity 错误