[IOS] study notes input detection UITextField - A restriction can only enter numbers and decimal point

Taking advantage of a recent vacation time, watching The Big Nerd Ranch's iOS programming, thinking back again to review the basics of iOS development

So start recording from a few minor problems encountered in the process of learning

The fourth chapter in the book have app to achieve a temperature conversion, the overall implementation is not difficult, but this time the focus is to use the input record UITextFieldDelegate commissioned limit of UITextField

 

UITextFieldDelegate which has a function

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool

Briefly, this is through request function processes the input, and then returns bool value, corresponding to whether the modified text

The original claims is to limit the TextField can only enter a decimal point, we have been given the associated implementation

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let existingTextHasDecimalSeparator = textField.text?.range(of: ".")
        let replacementTextHasDecimalSepatator = string.range(of: ".")
        if existingTextHasDecimalSeparator != nil,
            replacementTextHasDecimalSepatator != nil {
            return false
        } else {
            return true
        }

}

Achieve is very simple, nothing more than the use of the Swift in the range string method, string and string input to be entered in decimal to find

Leaving behind an after-school problem: require the use of prohibited CharacterSet implement input letters, direct implementation of the restrictions can only enter numbers and decimal points here I

First, initialize containing only a decimal point and numbers CharacterSet

let characterSet = CharacterSet.init(charactersIn: ".0123456789")

Then the same is carried out to find characterSet characters in replacementString, if the result is not empty, false

if string.rangeOfCharacter(from: characterSet) == nil {
            return false
}

Wrote all these previous textField function, the compiler will find a running problem - the failure of the delete key

To seriously look at documentation, will find that actually press the Delete key when textField function has also been called, but replacementString will be an empty string, while the front does not consider this issue, it will lead to failure of the delete key

After modifying the following

if string.rangeOfCharacter(from: characterSet) == nil,
    !string.isEmpty {
    return false
}

Guess you like

Origin www.cnblogs.com/slbgggg01/p/12188021.html