0

I have a UIView with a UILabel and a UITextField:

+--------------+
| label        |
|              |
| +-----------+|
| | textField ||
| +-----------+|
+--------------+

I want to select or focus the textField when I touch the label.

Scott Jungwirth
  • 6,105
  • 3
  • 38
  • 35

2 Answers2

1

Change your container UIView to a UIControl and in your ViewController.viewDidLoad add the following:

    textFieldContainer.addTarget(textField,
      action: #selector(becomeFirstResponder),
      for: .touchUpInside)

This will cause a touchUpInside event on the textFieldContainer to focus the textField

Scott Jungwirth
  • 6,105
  • 3
  • 38
  • 35
  • 2
    Or use a `UITapGestureRecognizer` with your container view. – rmaddy Mar 24 '17 at 21:13
  • @rmaddy in terms of simplicity, wouldn't this be a better choice than a GestureRecog? – Jay Mar 24 '17 at 22:36
  • @Jay It is not as clean. The ammount of code adding a UITapGestureRecognizer is sameish, but you get the benefits of being able to handle multiple gestures and having more control in the same view while the code being more clean and readable. –  Mar 25 '17 at 15:21
1

1: Add a UITapGestureRecognizer to your UILabel or your UIView as you wish

2: and handle the action from the tapGesture to fire start editing the textfield on tap.

Don't forget to set the UILabel to userInteractionEnabled = true if you add the tap gesture to the label.

Community
  • 1
  • 1