【发布时间】:2018-04-03 23:43:42
【问题描述】:
我创建了一个视图控制器,其中包含带有自定义单元格的 UITableView 和 xib。在自定义单元格 xib 中添加了 UITextField。现在我已将UITexField 的代表连接到自定义单元 xib 的文件所有者,并在视图控制器中添加了以下代码:
extension MyViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.endEditing(true)
return true
}
}
上面的方法没有被调用。
如果我在cellForRowAtindexPath 中添加以下代码,它会起作用:
cell.myTextField.delegate = self
谁能帮助我,为什么将UITextField 委托连接到自定义单元格中的文件所有者不起作用。
编辑
我是这样注册笔尖的:
myTableView.register(UINib(nibName: "MyCustomTableViewCell", bundle: nil), forCellReuseIdentifier: "mycustomcellreuseidentifier")
在cellForRowAtindexPath:
let cell = tableView.dequeueReusableCell(withIdentifier: "mycustomcellreuseidentifier", for: indexPath) as! MyCustomTableViewCell
除了UITextField 的@IBOutlet 之外,我没有在MyCustomTableViewCell 中添加任何代码。
编辑 - 在@Puneet Sharma 和@Francesco Deliro 的帮助下
尝试以下代码:
let myCustomCellNib = UINib(nibName: "MyCustomTableViewCell", bundle: nil)
myCustomCellNib.instantiate(withOwner: self, options: nil)
myTableView.register(myCustomCellNib, forCellReuseIdentifier: "mycustomcellreuseidentifier")
正如@Puneet Sharma 建议在 nib 中更改文件的所有者。我通过将类名添加到MyViewController,在身份检查器中进行了以下更改:
还是不行。
我应该去:
cell.myTextField.delegate = self
在cellForRowAtindexPath.
【问题讨论】:
-
执行此操作后,您是否在文本字段委托属性上创建了与文件所有者的连接?
-
是的,我也这样做了。
-
按 command+S 保存 nib 文件,然后尝试 agian。
-
@PuneetSharma - 做到了。事实上,我也尝试过退出 xcode。
-
我上面已经提到了。
标签: ios swift uitableview uitextfield