我是xcode / swift的新手,并且一直在网上关注以下示例,以将设置包添加到我的应用中。我正在努力的是如何限制用户可以在文本化设置中输入的字符数? root.plist似乎没有此选项,此Set the maximum character length of a UITextField in Swift似乎是针对应用程序内的文本字段的,而不是针对设置中已更改的文本字段的。请有人能指出正确的方向。
将TextField的委托设置为self并使ViewController符合UITextFieldDelegate
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let textFieldText = textField.text,
let rangeOfTextToReplace = Range(range, in: textFieldText) else {
return false
}
let substringToReplace = textFieldText[rangeOfTextToReplace]
let count = textFieldText.count - substringToReplace.count + string.count
return count <= 10 //number of characters
}
在要设置它的文件内设置UITextFieldDelegate方法。
1)在viewDidLoad方法中编写此代码。
myTextField.Delegate = self
2)实现shouldChangeCharactersIn textFieldDelegate的方法。
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let yourTextFieldLenghth = 4
if textField == myTextField {
let currentString: NSString = textField.text! as NSString
let newString: NSString =
currentString.replacingCharacters(in: range, with: string) as NSString
return newString.length <= yourTextFieldLenghth
}
return false
}