Home > other >  Adding UITextField() to UI programmatically, cannot tap on field to get keyboard
Adding UITextField() to UI programmatically, cannot tap on field to get keyboard

Time:07-03

I've been doing iOS development for a long time and I've never run into this before. The UITextField appears in the UI, it is correctly sized and placed by the constraints I've given it, but when I tap/click on it and doesn't respond. The cursor doesn't appear in the field and the keyboard doesn't show up.

let textfield = UITextField()
textfield.translatesAutoresizingMaskIntoConstraints = false
self.contentview.addSubview(textfield)
textfield.keyboardType = .numberPad
textfield.borderStyle = .roundedRect
textfield.text = "stuff"
// and then I set up constraints which are working as expected

I've double checked my simulator to make sure it isn't a soft keyboard issue.

I don't need any specialized UITextFieldDelegate behavior, I just need to standard behavior that tapping will cause it to become first responder, set the cursor there, and open the keyboard. When I add a UITextField via a storyboard, I don't need to set a delegate in order to get this behavior, so I can't imagine I would need to create specialized delegate code in order to get this basic behavior.

Just to test if something else was wrong, I've tried programmatically forcing the textfield to become first responder and that works.

I've tried forcing this to be true, just in case:

textfield.isUserInteractionEnabled = true

but that didn't change anything.

Any ideas? Why isn't my programmatically created UITextField accepting taps?


EDIT: Got an excellent suggestion to check out the Hierarchy Inspector to see if anything else is on top of it. It looks like I don't have anything on top of it: Here's a screenshot of the sim and of the hierarchy inspector turned a bit to the side so you can see the layers.

There isn't anything in front of the UITextField. (The UITextField has like 4 internal layers, but nothing is in front of them.)

screenshot of simulator

View Hierarchy Inspector

CodePudding user response:

As we have discussed in the comments under the OP, it's always a good idea to check the view hierarchy in the View Hierarchy Inspector to see if the frame is laid out properly and also if perhaps some other view isn't covering the other view which should become the first responder.

The view hierarchy inspector can be found here once the app is running on a simulator or a device.

view hierarchy inspector

  • Related