Reputation: 4962
I have a UITextField with an outlet called newscore. I am trying to run a block of code when the UITextfield (particularly newscore) is tapped and the keyboard is brought up, or when the user is begin editing the UITextfield.
I can't seem to figure out the proper function to do this.. Is it similar to the code below (the code doesn't work) or is the function called something else?
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
//Run block of code
}
Upvotes: 0
Views: 161
Reputation: 862
class ViewController: UITextFieldDelegate {
override func viewDidLoad() {
super.viewDidLoad()
textField.delegate = self
}
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
return true
}
func textFieldDidBeginEditing(_ textField: UITextField) {
}
}
Upvotes: 0
Reputation: 781
The functions
textFieldShouldBeginEditing:
which returns a Bool, or
textFieldDidBeginEditing:
are precisely what you want. All you need to do is make this class that your code is running in conform to the UITextFieldDelegate protocol, which is done by writing
class TheClass: PossibleSuperclass, PossibleProtocol, UITextFieldDelegate {...
and then officially set the delegate of the textfield to be your class either by using
theTextfield.delegate = self
in some startup/initialisation code, or by making a "delegate" outlet from the textfield to the class object in Interface Builder.
Upvotes: 1
Reputation: 22343
It's the right function. You need to set the delegate of your field like that:
yourTextfield.delegate = self
Also you need to set the Delegate in your class like that:
class YourClass : UIViewController, UITextFieldDelegate
Upvotes: 2
Reputation: 898
That function is correct.
If it is not being called, just check that text field delegate correct
Upvotes: 1