Josh O'Connor
Josh O'Connor

Reputation: 4962

On click of a UITextField, I want to run some code

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

Answers (4)

Anand Khanpara
Anand Khanpara

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

Richard Birkett
Richard Birkett

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

Christian
Christian

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

vichevstefan
vichevstefan

Reputation: 898

That function is correct.

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

Upvotes: 1

Related Questions