I am new to swift and have been stuck on this for hours. I am trying to recognize when a UITextField is tapped by the user, and call some function. For some reason I keep getting "unrecognized selector sent to instance". Here is my attempt at a solutionand Here is the error thrown
Any help is greatly appreciated!
Your selector is not pointing to the method! Try this instead:
textField.addTarget(self, action: #selector(ViewController.tapped(_:)), for: UIControlEvents.touchDown)
Also, instead of this approach you could also set ViewController
as the delegate for textField
and implement this:
extension ViewController: UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
print("tapped")
textField.backgroundColor = UIColor.blue
}
}
Use: action: #selector(ViewController.tapped())
Also, below that, add this: self.textField.delegate = self
you can simply perform you action in UITexFieldDelegate, by making
myTextField.delegate = self
and use the method
optional public func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool{
//perform you action here
return true
}
instead of finding a way to get tap event you can use textFieldDidBeginEditing function:
class ViewController: UIViewController, UITextFieldDelegate
{
@IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
textField.delegate = self;
// Do any additional setup after loading the view, typically from a nib.
}
func textFieldDidBeginEditing(textField: UITextField) {
print("TextField did begin editing method called")
}
func textFieldDidEndEditing(textField: UITextField) {
print("TextField did end editing method called")
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.