user6487002
user6487002

Reputation:

How to detect tap on UITextField for Swift 2?

Is there an documentation or example on how do I do it in Swift 2?

I have read many articles but it doesn't provide much details beside jumping into the codes which are mostly done in Objective-C / Swift 1.

Upvotes: 0

Views: 512

Answers (2)

Sunil Prajapati
Sunil Prajapati

Reputation: 473

You can set tag on textfield in Attribute Inspector or through programatically

 myTextfield.tag = 1 //AnyValue
 myTextfield.delegate = self

Now, Implement textfield delegate method and check for which textfield edited

 func textFieldShouldBeginEditing(textField: UITextField) -> Bool {

    if textField.tag == 1{
       //do here you want
    }
    return true
 } 

Upvotes: 1

Emptyless
Emptyless

Reputation: 3051

You can check if a UITextField became first responder to know if one was tapped. You need to set the delegate of UITextField for example:

@IBOutlet weak var textField: UITextField! { didSet { textField.delegate = self } }

Where self is a UIViewController conforming to UITextFieldDelegate

Now you can check if a UITextField became first responder with:

func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
    print("textField did became first responder")
    return true
}

You return true to let the textfield become first responder (unless that is not the behaviour you wish, then return false) and before the return statement you can do anything you want.

Upvotes: 0

Related Questions