将UITextFieldDelegate用于多个字段

时间:2016-10-07 12:15:14

标签: ios swift uitextfield uitextfielddelegate

我有以下代码阻止用户在.中输入多个句点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
 }
}

1 个答案:

答案 0 :(得分:6)

请用

更改此行

来自:

let periodsInTextField = myTextField.text!.componentsSeparatedByString(".").count - 1

致:

let periodsInTextField = textField.text!.componentsSeparatedByString(".").count - 1