如何将UITextField
中的字符数限制为10
,如果用户输入的数字超过10
,则只记录前10个字符?
答案 0 :(得分:5)
此解决方案还可以处理用户粘贴文本或点击删除键。
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let length = count(textField.text.utf16) + count(string.utf16) - range.length
return length <= 10
}
答案 1 :(得分:2)
通过实施UITextFieldDelegate
。
class ViewController: UIViewController, UITextFieldDelegate {
textField(textField: UITextField!,
shouldChangeCharactersInRange range: NSRange,
replacementString string: String!) -> Bool {
var shouldChange = false
if countElements(textField.text) < 10 {
shouldChange = true
}
return shouldChange
}
}
答案 2 :(得分:0)
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// You can check for other things besides length here as well.
return isValidLength(textField: textField, range: range, string: string)
}
private func isValidLength(textField: UITextField, range: NSRange, string: String) -> Bool {
let length = ((textField.text ?? "").utf16).count + (string.utf16).count - range.length
return length <= 10
}
这解决了@Ivan问的问题:
计数方法是什么?当前正在使用Swift 3。
它也有助于检查其他情况,而不会过于拥挤一种方法。例如,可以执行以下操作来检查多个条件,同时使函数保持较小:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return isValidKey(string: string) && isValidLength(textField: textField, range: range, string: string)
}
private func isDeleteKey(string: String) -> Bool {
if let character = string.cString(using: String.Encoding.utf8) {
let isBackSpace = strcmp(character, "\\b")
if (isBackSpace == -92) {
return true
}
}
return false
}
private func isNumericKey(string: String) -> Bool {
return string.rangeOfCharacter(from: NSCharacterSet.decimalDigits) != nil
}
private func isValidLength(textField: UITextField, range: NSRange, string: String) -> Bool {
let length = ((textField.text ?? "").utf16).count + (string.utf16).count - range.length
return length <= 10
}
private func isValidKey(string: String) -> Bool {
return isDeleteKey(string: string) || isNumericKey(string: string)
}
我还要提到,要使用textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
,您需要遵循文本字段的UITextFieldDelegate
和set the delegate。例如:
class MyClass: UITextFieldDelegate {
@IBOutlet weak var textField: UITextField!
init() {
textField.delegate = self
}
}