Reputation: 416
I want to have an action when a certain textfield is pressed. I have tried
func textFieldDidBeginEditing(_ textField: UITextField) {
if textField == myTextField {
print("pressed")
}
}
but this didn't work for me. Does anyone have any solutions? Thanks
Upvotes: 1
Views: 4371
Reputation: 56
This function is the callback from UITextFieldDelegate. But it will only be fired if the class with this is connected to your UITextField's delegate.
simple Example using an iOS ViewController:
class yourViewController: UIViewController, UITextFieldDelegate
{
/* Make sure that your variable 'myTextField' was created using an IBOutlet from your storyboard*/
@IBOutlet var myTextField : UITextField!
override func ViewDidLoad()
{
super.viewDidLoad()
myTextField.delegate = self // here you set the delegate so that UITextFieldDelegate's callbacks like textFieldDidBeginEditing respond to events
}
func textFieldDidBeginEditing(_ textField: UITextField) {
if textField == myTextField {
print("pressed")
}
}
}
Make sure though that you understand the concept of the delegation pattern event handling, and how a delegate captures and posts events like this one for instance. A lot of Cocoa GUI components use this design. these are some useful links.
https://docs.swift.org/swift-book/LanguageGuide/Protocols.html
https://developer.apple.com/documentation/uikit/uitextfielddelegate
http://www.andrewcbancroft.com/2015/03/26/what-is-delegation-a-swift-developers-guide/
Upvotes: 2