首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >当UITextField发生变化时,如何检查?

当UITextField发生变化时,如何检查?
EN

Stack Overflow用户
提问于 2015-02-08 22:16:24
回答 7查看 305.3K关注 0票数 341

我正在尝试检查文本字段何时发生更改,相当于用于textView - textViewDidChange的函数。到目前为止,我已经这样做了:

代码语言:javascript
复制
  func textFieldDidBeginEditing(textField: UITextField) {
        if self.status.text == "" && self.username.text == "" {
            self.topRightButton.enabled = false
        } else {   
            self.topRightButton.enabled = true
        }
    }

哪种方式有效,但文本字段一按下,topRightButton就会启用,我想只在实际键入文本时启用它?

EN

回答 7

Stack Overflow用户

发布于 2016-02-25 23:34:49

到目前为止我处理它的方式:在UITextFieldDelegate

代码语言:javascript
复制
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
{
    // text hasn't changed yet, you have to compute the text AFTER the edit yourself
    let updatedString = (textField.text as NSString?)?.stringByReplacingCharactersInRange(range, withString: string)

    // do whatever you need with this updated string (your code)


    // always return true so that changes propagate
    return true
}

Swift4版本

代码语言:javascript
复制
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let updatedString = (textField.text as NSString?)?.replacingCharacters(in: range, with: string)
    return true
}
票数 35
EN

Stack Overflow用户

发布于 2016-09-27 16:50:47

Swift 3

代码语言:javascript
复制
 textField.addTarget(self, action: #selector(ViewController.textFieldDidChange(sender:)), for: UIControlEvents.editingChanged)
票数 14
EN

Stack Overflow用户

发布于 2016-10-17 16:46:05

如果你想检查每一次按键,textField(_:shouldChangeCharactersIn:replacementString:)在Xcode8,Swift3中对我是有效的。

代码语言:javascript
复制
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    // Whatever code you want to run here.
    // Keep in mind that the textfield hasn't yet been updated,
    // so use 'string' instead of 'textField.text' if you want to
    // access the string the textfield will have after a user presses a key

    var statusText = self.status.text
    var usernameText = self.username.text

    switch textField{
    case self.status:
        statusText = string
    case self.username:
        usernameText = string
    default:
        break
    }

    if statusText == "" && usernameText == "" {
        self.topRightButton.enabled = false
    } else {   
        self.topRightButton.enabled = true
    }

    //Return false if you don't want the textfield to be updated
    return true
}
票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28394933

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档