我有以下代码阻止用户在.
中输入多个句点UITextField
,它运行正常,但我想对其他两个textField执行相同操作,这怎么可以可以吗?
我尝试将delegate
分配给多个字段并且它不起作用,它只适用于第一个响应的第一个字段。
class UserInputViewController: UIViewController, UITextFieldDelegate{
override func viewDidLoad() {
super.viewDidLoad()
self.myTextField.delegate = self
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let periodsInTextField = myTextField.text!.componentsSeparatedByString(".").count - 1
if (periodsInTextField > 0 && string == "."){
return false
}
return true
}
}
编辑(答案):以下是基于@KKRocks'回答如下。
class UserInputViewController: UIViewController, UITextFieldDelegate{
override func viewDidLoad() {
super.viewDidLoad()
self.myTextField.delegate = self
self.secondTextField.delegate = self
self.thirdTextField.delegate = self
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let periodsInTextField = textField.text!.componentsSeparatedByString(".").count - 1
if (periodsInTextField > 0 && string == "."){
return false
}
return true
}
}
答案 0 :(得分:6)
请用
更改此行来自:
let periodsInTextField = myTextField.text!.componentsSeparatedByString(".").count - 1
致:
let periodsInTextField = textField.text!.componentsSeparatedByString(".").count - 1