Using `textField:shouldChangeCharactersInRange:`, how do I get the text including the current typed character?

前端 未结 10 2017
粉色の甜心
粉色の甜心 2020-12-02 05:23

I\'m using the code below to try and have textField2\'s text content get updated to match textField1\'s whenever the user types in textField1

相关标签:
10条回答
  • 2020-12-02 06:18

    If you need to replace the textfield text with this you can use my solution (Swift 3): https://gist.github.com/Blackjacx/2198d86442ec9b9b05c0801f4e392047

    After the replacement you can just get textField.text to retrieve the composed text.

    0 讨论(0)
  • 2020-12-02 06:19

    use guard

    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
            guard case let textFieldString as NSString = textField.text where
                textFieldString.stringByReplacingCharactersInRange(range, withString: string).length <= maxLength else {
                    return false
            }
            return true
        }
    
    0 讨论(0)
  • 2020-12-02 06:21

    Swift 3

    Based on the accepted answer, the following should work in Swift 3:

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

    Note

    Both String and NSString have methods called replacingCharacters:inRange:withString. However, as expected, the former expects an instance of Range, while the latter expects an instance of NSRange. The textField delegate method uses an NSRange instance, thus the use of NSString in this case.

    0 讨论(0)
  • 2020-12-02 06:29

    This is the code you need,

    if ([textField isEqual:self.textField1])
      textField2.text = [textField1.text stringByReplacingCharactersInRange:range withString:string];
    
    0 讨论(0)
提交回复
热议问题