0

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

}
halfer
  • 19,824
  • 17
  • 99
  • 186
Josh O'Connor
  • 4,694
  • 7
  • 54
  • 98
  • possible duplicate of [How to get UITextField Tap Event?](http://stackoverflow.com/questions/10045095/how-to-get-uitextfield-tap-event) – Lyndsey Scott Apr 30 '15 at 23:02

4 Answers4

2

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
Christian
  • 22,585
  • 9
  • 80
  • 106
1

That function is correct.

If it is not being called, just check that text field delegate correct

vichevstefan
  • 898
  • 7
  • 16
1

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.

Richard Birkett
  • 771
  • 9
  • 20
0

class ViewController: UITextFieldDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        textField.delegate = self
    }
    
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        return true
    }
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        
    }
    
}
Anand Khanpara
  • 846
  • 8
  • 8