ios - swift 3 : retrieving text from a UITextField in a custom UITableViewCell

标签 ios swift uikit

我正在尝试从自定义单元格中的 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/

相关文章:

ios - 限制模糊效果

ios - 自定义 iOS 键盘 – 按键速度太慢

json - Swift ISO 8601 日期格式

ios - 从容器 View 中的另一个 View Controller 加载 View Controller

ios - WKWebView 中的嵌入推文有时无法完全加载

ios - MFMailComposeViewController Bar titleText 和 UIbarbuttons 不使用外观代理提供的自定义字体

ios - 插入行后 UITableViewCell 动态高度中断

ios - Apple Mach-O 链接器警告 : how to get rid of it but not affect my friend

ios - 如何处理自定义 Tableview 单元格 iOS 中的“收藏夹”按钮点击?

ios - 删除推送通知支持一段时间