【发布时间】:2015-01-28 16:43:52
【问题描述】:
如何在 Swift 中将用户的 TextField 输入限制为数字?
【问题讨论】:
-
您在使用情节提要吗?如果您在属性检查器中有一个选项只允许数字字符
标签: ios swift xcode cocoa-touch uitextfield
如何在 Swift 中将用户的 TextField 输入限制为数字?
【问题讨论】:
标签: ios swift xcode cocoa-touch uitextfield
第一个你必须继承你自己的 UITextViewDelegate 类 类
class ViewController: UIViewController, UITextViewDelegate {
第二次添加 IBOutlet
@IBOutlet weak var firstName: UITextField!
第三你必须确保这个对象正在使用
override func viewDidLoad() {
super.viewDidLoad()
firstName.delegate = self
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField == firstName {
let allowedCharacters = "1234567890"
let allowedCharacterSet = CharacterSet(charactersIn: allowedCharacters)
let typedCharacterSet = CharacterSet(charactersIn: string)
let alphabet = allowedCharacterSet.isSuperset(of: typedCharacterSet)
let Range = range.length + range.location > (fnameTF.text?.count)!
if Range == false && alphabet == false {
return false
}
let NewLength = (fnameTF.text?.count)! + string.count - range.length
return NewLength <= 10
} else {
return false
}
}
【讨论】:
对于任何寻求简短答案的人,我发现this 非常有用。
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// remove non-numerics and compare with original string
return string == string.filter("0123456789".contains)
}
适用于 XCode 10.1、Swift 4.2
【讨论】:
在 swift 4.1 和 Xcode 10 中
将 UITextFieldDelegate 添加到您的班级
class YourViewController: UIViewController, UITextFieldDelegate
然后在你的 viewDidLoad()
中编写这段代码yourTF.delegate = self
编写此文本字段委托函数
//MARK - UITextField Delegates
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
//For numers
if textField == yourTF {
let allowedCharacters = CharacterSet(charactersIn:"0123456789")//Here change this characters based on your requirement
let characterSet = CharacterSet(charactersIn: string)
return allowedCharacters.isSuperset(of: characterSet)
}
return true
}
【讨论】:
您可以使用UITextFieldDelegate 的shouldChangeCharactersInRange 方法将用户的输入限制为数字:
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
}
为 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
}
【讨论】:
join("", components) 在 Swift 2.0 中中断,改为使用 components.joinWithSeparator("")。
UITextFieldDelegate??
iOS 没有提供这样的功能,您可以将文本字段指定为仅接受数字字符。唯一的方法是 UITextFieldDelegate 方法之一,如下所示,
(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
您需要实现以下方法并通过以下正则表达式截取输入的字符
"^([0-9]+)?(\\.([0-9]{1,2})?)?$"
或
[NSCharacterSet decimalDigitCharacterSet]
可以判断输入的字符是否为数字,如果匹配正则表达式或字符集则返回YES,否则返回NO。
【讨论】: