How to restrict UITextField to take only numbers in Swift?

后端 未结 30 799
难免孤独
难免孤独 2020-12-04 08:40

I want the user to only enter numeric values in a UITextField. On iPhone we can show the numeric keyboard, but on iPad the user can switch to any keyboard.

相关标签:
30条回答
  • 2020-12-04 08:58
    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        if let numRange = string.rangeOfCharacterFromSet(NSCharacterSet.letterCharacterSet()) {
            return false
        } else {
            return true
        }
       }
    
    0 讨论(0)
  • 2020-12-04 09:01

    The following is the code I used in Swift 3.0 adapted from Mr H's code. Differences are because:

    a) Delegate function declaration has changed in Swift 3.0. New declaration here

    b) NSCharacterSet declaration has changed.

    func textField(_ shouldChangeCharactersIntextField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
    {
    
            let inverseSet = NSCharacterSet(charactersIn:"0123456789").inverted
    
            let components = string.components(separatedBy: inverseSet)
    
            let filtered = components.joined(separator: "")
    
            return string == filtered
    
    }
    
    0 讨论(0)
  • 2020-12-04 09:02

    You can use shouldChangeCharactersInRange along with String extension method to check if the input string is number or not.

    extension String  {
    
        var isNumber : Bool {
            get{
                return !self.isEmpty && self.stringWithoutWhitespaces.rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil
            }
        }
    
        var stringWithoutWhitespaces: String {
            return self.replacingOccurrences(of: " ", with: "")
        }
    
    }
    
    //Mark: shouldChangeCharactersInRange
    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        // return true if the string only contains numeric characters
        let isValid = string.stringWithoutWhitespaces.isNumber 
        return valid
    }
    
    0 讨论(0)
  • 2020-12-04 09:03

    Here's an cleaner solution:

     guard CharacterSet(charactersIn: "123456789").isSuperset(of: CharacterSet(charactersIn: string)) else {
         return false
     }
     return true
    

    For decimals just add ., example 123456789.

    0 讨论(0)
  • 2020-12-04 09:04
    Swift 2.0
    
    func textField(textField: UITextField,
        shouldChangeCharactersInRange range: NSRange,
        replacementString string: String) -> Bool {
    
            let inverseSet = NSCharacterSet(charactersInString:"0123456789").invertedSet
    
            let components = string.componentsSeparatedByCharactersInSet(inverseSet)
    
            let filtered = components.joinWithSeparator("")
    
            return string == filtered
    
      }
    
    0 讨论(0)
  • 2020-12-04 09:05

    For allow some charactors

    func CheckAddress(string:String) -> Bool  {
            let numberOnly = NSCharacterSet.init(charactersIn: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-@,&#/")
            let stringFromTextField = NSCharacterSet.init(charactersIn: string)
            return numberOnly.isSuperset(of: stringFromTextField as CharacterSet)
        }
    
    print("\(CheckAddress(string: "123"))") //True
    print("\(CheckAddress(string: "asdf-"))") //True
    print("\(CheckAddress(string: "asd123$"))") //false
    
    0 讨论(0)
提交回复
热议问题