Reputation: 923
I faced something and I cannot understand it.
In the tutorial which I watched, instructor press (cntrl + click) delegate option and drag it into ViewController class. Then, textfield options become like the photo. I searched for a lot and I found an explanation ,but I couldn't understand it exactly.
Explanation : To be able to use UITextFieldDelegate methods, ViewController class must adopt this protocol. However, before using any method, we have to choose this delegate option.
I cannot understand this option. What is the benefit of it ?
Upvotes: 0
Views: 288
Reputation: 4849
so in order to use it and understand it try out these steps:
1 adopt UITextFieldDelegate protocol to your class like so
class MyViewController: UIViewController, UITextViewDelegate {
2 implement callback methods for the UITextViewDelegate. For example:
//MARK: UITextViewDelegate
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
print(textField.text ?? "")
return true
}
These methods are made for managing and validating text from the TextView. Maybe you should read about protocols.
Or if you don't understand why you are setting your delegate form the storyboard directly it's because this way you will not have an extra property declared in your class. I will be done seamlessly and you will not have this in your class:
@IBOutlet weak var myTextField: UITextField!
//...
override func viewDidLoad() {
super.viewDidLoad()
myTextField.delegate = self
}
Upvotes: 1
Reputation: 306
First add delegate to your view controller as UITextFieldDelegate
Only then the delegate functions can be used in the view controller.
And for the functions to work as expected, You have to set the textfield's delegate as self. Eg textfield.delegate = self
Setting the delegate of textfield as self is the programatic way of doing the same thing the instructor did (as you said).
Upvotes: 0