对多个字段使用 UITextFieldDelegate
Use UITextFieldDelegate for multiple fields
我有以下代码来防止用户在 UITextField
中输入多个句点 .
,它工作正常但我想对其他两个文本字段做同样的事情,如何这可以做到吗?
我尝试将 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
}
}
EDIT(Answer) :这是根据下面@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
}
}
请将此行更改为
发件人:
let periodsInTextField = myTextField.text!.componentsSeparatedByString(".").count - 1
收件人:
let periodsInTextField = textField.text!.componentsSeparatedByString(".").count - 1
我有以下代码来防止用户在 UITextField
中输入多个句点 .
,它工作正常但我想对其他两个文本字段做同样的事情,如何这可以做到吗?
我尝试将 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
}
}
EDIT(Answer) :这是根据下面@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
}
}
请将此行更改为
发件人:
let periodsInTextField = myTextField.text!.componentsSeparatedByString(".").count - 1
收件人:
let periodsInTextField = textField.text!.componentsSeparatedByString(".").count - 1