我有一个iOS
Xcode 7.3 Swift2
项目,我正在做。它有不同的UITextFields
,它们被限制在3位数,特别是数字。它们被分配给UITextFieldDelegate
,它工作得很好。
下面是我限制它们的地方:
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
guard let text = textField.text else { return true }
let newLength = text.characters.count + string.characters.count - range.length
let limitLength = 3
if newLength > limitLength {
return false
}
let numberOnly = NSCharacterSet.init(charactersInString: "0123456789")
let stringFromTextField = NSCharacterSet.init(charactersInString: string)
let strValid = numberOnly.isSupersetOfSet(stringFromTextField)
return strValid
}
然而,一些UITextFields
需要限制为数字,并且还限制为单个数字,我如何在上面的部分中建立这一点,仅针对那些特定的UITextFields
?
需要为单个数字的UITextFields
的名称为:
widthInches
lengthInches
我试着把这个放在第一个警卫区之后,但没有成功:
guard let text2 = widthInches.text else { return true }
let newLength2 = text2.characters.count + string.characters.count - range.length
let limitLength2 = 3
if newLength2 > limitLength2 {
return false
}
5条答案
按热度按时间0yg35tkg1#
您也可以尝试将此代码用于限制文本字段
实际上我在这里使用了textfield标签。因为自定义textfield。如果你在这个条件下使用自定义textfield像TextfieldEffect标签将帮助你限制Textfield。
我希望这对你有帮助。
f87krz0w2#
函数
shouldChangeCharactersInRange
将特定的textField作为参数之一传入,您可以查看它是否指向与您要缩短的示例相同的示例,如下所示:假设所有其他要求都是相同的(仅数字),这将起到作用。
还有其他方法,例如,您可以子类化UITextField并添加一个limitLength字段,然后在委托中使用该字段,但仅对于两个异常,这可能有点过头了。
4nkexdtk3#
Hello在您的
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
中,textField
参数是触发此事件的textField,因此您可以检查您的textfield对象,如果等于其中一个对象,则执行不同的行为我希望这对你有帮助,
ehxuflar4#
这会根据UTF-16表示法来计算字符数,如range。length是以UTF-16为基数。如果您需要以其他方式计算字符数,则表达式可能会变长。如果您只想输入数字,则使用
textField.keyboardType = UIKeyboardTypeDecimalPad
。如果您需要特定的textFields,则添加标记并比较它们,如果它们相等,则可以为此实现您的特定代码。请查看此链接以了解详细答案:http://www.globalnerdy.com/2016/05/24/a-better-way-to-program-ios-text-fields-that-have-maximum-lengths-and-accept-or-reject-specific-characters/
t5zmwmid5#
update for swift 3添加这个类并将其命名为TextField. swift。它将在故事板上添加限制输入。
或在此处下载-〉TextField.swift