user3758317
user3758317

Reputation: 117

UITextField doesn't work when added via code

I am having a problem with adding UITextField via code. When I use this simple code inside empty view controller all work fine:

let textField = UITextField(frame: CGRect(x: 10, y: 10, width: 200, height: 20))
textField.text = "test"
scrollView.addSubview(textField)

But inside my custom UIScrollView for some reason it won't work (editing don't start).

I tried to set userInteractionEnabled for textField and also for superview but that doesn't help. I am not sure how I can debug to see which property is blocking editing. No keyboard is popping up; I can't type inside simulator and/or make selections. What is also strange that other controls such as UIButton work perfect and receive touches.

As can be seen, I didn't add delegate, but it works perfectly good on empty UIViewController without it.

po textField.canBecomeFirstResponder() returns true.

Upvotes: 2

Views: 323

Answers (2)

Icaro
Icaro

Reputation: 14845

I was reading apple documentation and I find this:

If the value of this property is true, the scroll view delays handling the touch-down gesture until it can determine if scrolling is the intent. If the value is false , the scroll view immediately calls touchesShouldBegin:withEvent:inContentView:. The default value is true.

And This from apple documentation:

This method traverses the view hierarchy by calling the pointInside:withEvent: method of each subview to determine which subview should receive a touch event. If pointInside:withEvent: returns true, then the subview’s hierarchy is similarly traversed until the frontmost view containing the specified point is found. If a view does not contain the point, its branch of the view hierarchy is ignored.

Upvotes: 2

NSIRLConnection
NSIRLConnection

Reputation: 104

Set scrollView.delaysContentTouches to NO.

You may have to come up with your own logic for turning it off/on depending on whether or not accidentally touching a control inside the scrollView becomes an issue.

You can also just tap and hold on the textField without scrolling. It should bring up the keyboard, but most users probably won't know to do that.

Upvotes: 1

Related Questions