How to restrict UITextField to take only numbers in Swift?

后端 未结 30 912
难免孤独
难免孤独 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条回答
  •  Happy的楠姐
    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
    
    }
    

提交回复
热议问题