我正在尝试从自定义单元格中的 UITextField
检索文本,并将该值分配给我的 View Controller 中的 self.email
变量。当我在 textFieldDidEndEditing
函数中设置断点时,我可以看到 textField
的值按预期分配给了 self.email
,但是@IBAction doneButtonDidPress
函数中的变量 self.email
为 nil。
问题:为什么self.email
的值变成了nil
?
extension ViewController: UITextFieldDelegate {
func textFieldDidEndEditing(_ textField: UITextField) {
if let text = textField.text {
self.email = text
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
let cell = self.tableView.cellForRow(at: IndexPath(row: 2, section: 0)) as! AboutCell
cell.textView?.becomeFirstResponder()
return true
}
}
我正在使用 UITableViewController
,这就是我创建单元格的方式:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch indexPath.row {
case 0:
let cell = tableView.dequeueReusableCell(withIdentifier: "profilePhotoCell")! as! ProfilePhotoCell
cell.delegate = self
return cell
case 1:
let cell = tableView.dequeueReusableCell(withIdentifier: "textFieldCell")! as! TextFieldCell
cell.textField.delegate = self
cell.textLabel?.text = "Email"
return cell
default:
let cell = tableView.dequeueReusableCell(withIdentifier: "aboutCell")! as! AboutCell
cell.textView.delegate = self
return cell
}
}
@IBAction
函数:
@IBAction func doneButtonDidPress(_ sender: Any) {
print(self.email) // returns nil
}
最佳答案
解决方案是将self.tableView.endEditing(true)
放在@IBAction func doneButtonDidPress(_:)
中。
关于ios - swift 3 : retrieving text from a UITextField in a custom UITableViewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45950517/