使用 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
最佳答案
你的代码几乎没问题,但你崩溃了,因为那个单元格超出了范围,所以首先你必须滚动到开头(使其可见),然后你将能够在这样的 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/