Search code examples
swiftuitextfielduitextfielddelegate

Is there any way to make UITextFieldDelegate more dynamic in swift?


I nearly have a UITextFieldDelegate in a UIViewController,and I make

import UIKit

class testViewController: UIViewController,UITextFieldDelegate{

    @IBOutlet weak var textName: UITextField!

    override func viewDidLoad(){
       super.viewDidLoad()

       textName.delegate = self
    }

    func textFieldShouldReturn(textField: UITextField) -> Bool {
       return true
    }
}

it works very well. but my question is, when i have two, or three UITextFields, and have different function,what should i do? Is there any way to make UITextFieldDelegate more dynamic in swift? just like java do? I remember that java may do like that:

textName.delegate = UITextFieldDelegate{
   func textFieldShouldReturn(textField: UITextField) -> Bool {
       return true
    }
}

textAddress.delegate = UITextFieldDelegate{
   func textFieldShouldReturn(textField: UITextField) -> Bool {
       return true
    }
}

Solution

  • The delegate methods take a parameter that identifies the text field for which the demarcate methods are being called. You can use this to provide different behaviours for different text fields.