Get name of selected UITextField

Hi together,

I just joined this forum because I just started tp learn programming with swift.

I'm using XCode 11 with swift and want to try to create an app for my IOS devices :slight_smile:
I'm gained a litle experienced with perl ......

My very first question is how to get the active or activated UITextField after selecting?

I've two UITextFields and want to assign a date from the datepicker to assign the selected date to that UITextField I selected before.

Or I want to get the object I selectedfor further processing.

I just tried something like this to enter a text in the UITextField.text I selected before:

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

@IBOutlet weak var text1: UITextField!
@IBOutlet weak var text2: UITextField!

override func viewDidLoad() {
    // Do any additional setup after loading the view.

    text1.addTarget(self, action: #selector(eventHappened), for: .touchDown)

 @objc func eventHappened(textfield: UITextField) {
    print ("hallo")
    textfield.text = "hallo"


Thank's for any advice :smiley:

It depends what you want to do when you have tapped in the UITextField.

Normally, you would implement the UITextFieldDelegate protocol to intercept the various events that happen in a UITextField. Setting a selector for an action is not the best way to handle that kind of scenario and .touchDown is not the best action to intercept.

You should also investigate the UIResponder methods, especially canBecomeFirstResponder, becomeFirstResponder, canResignFirstResponder and resignFirstResponder. These get called when you tap into or out of a UITextField.

Hi, thanks a lot

I'll try to implment the way by delegates ....

Terms of Service

Privacy Policy

Cookie Policy