How do I check when a UITextField changes?

后端 未结 19 3236
情话喂你
情话喂你 2020-11-22 15:44

I am trying to check when a text field changes, equivalent too the function used for textView - textViewDidChange so far I have done this:

  fu         


        
19条回答
  •  盖世英雄少女心
    2020-11-22 16:33

    The way I've handled it so far: in UITextFieldDelegate

    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 version

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let updatedString = (textField.text as NSString?)?.replacingCharacters(in: range, with: string)
        return true
    }
    

提交回复
热议问题