检测用户何时在 UITableViewCell 中的 UITextField 中完成输入

Detect when user is done typing in a UITextField within a UITableViewCell

我在 UITableViewCell 中嵌入了 UITextField。我正在尝试实现一个类似于 Instagram 评论的功能,当用户在文本字段中有文本时,发送按钮被启用,如果没有文本,发送按钮不被启用。即使实现了 textFieldDidEndEditing,我似乎也无法检测到用户何时完成输入。此方法似乎只有在单击 return 按钮时才有效。有没有一种方法可以检测用户何时在文本字段中完成输入并且至少有一个字符,从而启用发送按钮?

我的代码:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
 ...
case .comment:
            let cell = tableView.dequeueReusableCellWithIdentifier(cellInfo.description, forIndexPath: indexPath) as! PictureInformationTableViewCell
            cell.sendMessageBtn.addTarget(self, action: "didTapSendMessageBtn:", forControlEvents: .TouchUpInside)
            cell
            cell.commentTextField.layer.borderWidth = 1
            cell.commentTextField.layer.borderColor = UIColor.whiteColor().CGColor
            cell.sendMessageBtn.layer.cornerRadius = 5
            if initBtn == false {
                cell.sendMessageBtn.enabled = false
            }
            buttonColor = cell.sendMessageBtn.tintColor
            cell.commentTextField.delegate = self
            //cell.commentTextField.addTarget(self, action: "didEndEditing:", forControlEvents: UIControlEvents.e)
            return cell
        }


func textFieldDidEndEditing(textField: UITextField) {
     let cell = tableView.dequeueReusableCellWithIdentifier(PictureInformation.comment.description, forIndexPath: NSIndexPath(forRow: 0, inSection: 3)) as! PictureInformationTableViewCell
     if let text = textField.text {
         initBtn = true
         if text.characters.count > 0 {
             cell.sendMessageBtn.enabled = true
             cell.sendMessageBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
             tableView.reloadInputViews()
         } else {
             cell.sendMessageBtn.enabled = false
             cell.sendMessageBtn.setTitleColor(buttonColor, forState: UIControlState.Normal)
             tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: 0, inSection: 3)], withRowAnimation: .None)
             tableView.reloadInputViews()
         }
     }
 }

为您的 textField 添加操作 EditingChanged 每当您向 textField 添加值时调用该操作。

更新 我在情节提要中添加了一个文本字段和一个按钮。我创建了两个插座,一个用于按钮,一个用于文本字段,并且我为我的文本字段添加了一个操作 (EditingChanged)。

您现在唯一需要做的就是 enabled/disable 按钮是:

@IBOutlet weak var btn: UIButton!
@IBOutlet weak var txtField: UITextField!

@IBAction func txtField_EditingChanged(sender: AnyObject) {
        if txtField.text?.characters.count > 0{
            btn.enabled = true
        }
        else{
            btn.enabled = false
        }
    }