我想限制用户可以在文本字段中使用的字符数。我从这个链接中获取了一个函数:Max length UITextField (Imanou Petit)
但是,在我的 viewDidLoad() 中,我有几个文本字段,我已经在引用委托(delegate),因为我希望当用户按下键盘上的 Return
键时键盘“返回”。这是我通过 textFieldShouldReturn
做的(我也有一个 touchesBegan 方法,但我希望用户也可以选择 Return
键):
func textFieldShouldReturn(textField: UITextField!) -> Bool {
self.stuffOneTextField.resignFirstResponder()
self.linkTextField.resignFirstResponder()
self.descriptionTextField.resignFirstResponder()
self.ogTextField.resignFirstResponder()
self.priceTextField.resignFirstResponder()
return true
}
如果我在下面的这个函数中添加到 viewDidLoad,那么键盘上的“返回”键就不起作用,它会限制所有的文本字段(我有 5 个)。
override func viewDidLoad() {
super.viewDidLoad()
self.stuffOneTextField.delegate = self
self.linkTextField.delegate = self
self.descriptionTextField.delegate = self
self.ogTextField.delegate = self
self.priceTextField.delegate = self
}
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
return newLength <= limitLength
}
我只需要限制 2 个文本字段。我试过只输入特定的 textField 名称而不是所有的 textField 作为 textField
s 然后它限制了 1 个 textField 并且不允许我输入其他的......很奇怪......
我该如何解决这个问题?
任何帮助都意义重大。
最佳答案
您将获得 textField
,它正在委托(delegate)函数中更改字符。在这里,您可以将其与要限制的特定字段进行比较:
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
guard let text = textField.text else { return true }
if !(textField == stuffOneTextField || textField == descriptionTextField) {
return true
}
let newLength = text.characters.count + string.characters.count - range.length
return newLength <= limitLength
}
另外,func textFieldShouldReturn(textField: UITextField!) -> Bool
给你一个文本字段,你可以调用 resignFirstResponder()
,如果是的话你想在那里做什么。
关于Swift:在不禁用/干扰其他功能的情况下限制文本字段中的字符#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33289553/