Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
311 views
in Technique[技术] by (71.8m points)

ios - Limit UITextField input to numbers in Swift

How can I get limit the user's TextField input to numbers in Swift?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use UITextFieldDelegate’s shouldChangeCharactersInRange method to limit the user's input to numbers:

func textField(textField: UITextField,
    shouldChangeCharactersInRange range: NSRange,
    replacementString string: String) -> Bool {

    // Create an `NSCharacterSet` set which includes everything *but* the digits
    let inverseSet = NSCharacterSet(charactersInString:"0123456789").invertedSet

    // At every character in this "inverseSet" contained in the string,
    // split the string up into components which exclude the characters
    // in this inverse set
    let components = string.componentsSeparatedByCharactersInSet(inverseSet)

    // Rejoin these components
    let filtered = components.joinWithSeparator("")  // use join("", components) if you are using Swift 1.2

    // If the original string is equal to the filtered string, i.e. if no
    // inverse characters were present to be eliminated, the input is valid
    // and the statement returns true; else it returns false
    return string == filtered
}

Updated for Swift 3:

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

    // Create an `NSCharacterSet` set which includes everything *but* the digits
    let inverseSet = NSCharacterSet(charactersIn:"0123456789").inverted

    // At every character in this "inverseSet" contained in the string,
    // split the string up into components which exclude the characters
    // in this inverse set
    let components = string.components(separatedBy: inverseSet)

    // Rejoin these components
    let filtered = components.joined(separator: "")  // use join("", components) if you are using Swift 1.2

    // If the original string is equal to the filtered string, i.e. if no
    // inverse characters were present to be eliminated, the input is valid
    // and the statement returns true; else it returns false
    return string == filtered  
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...