How shouldChangeCharactersInRange works in Swift?

前端 未结 7 692
不思量自难忘°
不思量自难忘° 2020-12-07 17:38

I\'m using shouldChangeCharactersInRange as a way of using on-the-fly type search.

However I\'m having a problem, shouldChangeCharactersInRange get

7条回答
  •  旧巷少年郎
    2020-12-07 17:58

    Swift 3 & 4

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

    Swift 2.2

    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        let textFieldText: NSString = textField.text ?? ""
        let txtAfterUpdate = textFieldText.stringByReplacingCharactersInRange(range, withString: string)
        callMyMethod(txtAfterUpdate)
    
        return true
    }
    
    func textFieldShouldClear(textField: UITextField) -> Bool {
        callMyMethod("")
        return true
    }
    

    Though the textField.text property is an optional, it cannot be set to nil. Setting it to nil is changed to empty string within UITextField. In the code above, that is why textFieldText is set to empty string if textField.text is nil (via the nil coalescing operator ??).

    Implementing textFieldShouldClear(_:) handles the case where the text field's clear button is visible and tapped.

提交回复
热议问题