UITextField ― Adding UIView for leftView - Can't get Focus

匿名 (未验证) 提交于 2019-12-03 08:57:35

问题:

The UITextFields in my app have placeholder text defined (in Interface Builder), and I cannot cause these fields to acquire focus (i.e. show the keyboard and allow editing) when I tap on the area occupied by the placeholder text. If I tap on the textfields in an area just outside the that of placeholder text (though still within the bounds of the textfiled itself), it acts as normal (i.e. the keyboard pops up and I can edit the content of the textfield). How can I fix this?

Thanks.

EDIT 1

Ok, I think I've got it. I'm also setting a blank view to the "leftView" property of these UITextFields. If I remove this, you can touch the UITextFields in the area of the placeholder text and it reacts as expected; I need this view for the leftView though. If you change the background color of this spacer view to red, you can see that it doesn't get in the way at all, so I don't know what's going wrong.

Why does this code cause this problem?

Thanks.

+(UIView*)getTextFieldLeftSpacerViewWithBackgroundColor:(UIColor*)backgroundColor andHeight:(CGFloat)height {     UIView *leftWrapper = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 8.0f, height)];     leftWrapper.autoresizingMask = UIViewAutoresizingNone;     [leftWrapper setOpaque:YES];     if(backgroundColor){leftWrapper.backgroundColor = backgroundColor;}     else{leftWrapper.backgroundColor = [UIColor clearColor];}     return [leftWrapper autorelease]; }  +(void)setTextFieldLeftSpacerForTextFieled:(UITextField*)textField {     if(textField)     {         UIView *spacer = [MYViewController getTextFieldLeftSpacerViewWithBackgroundColor:nil andHeight:textField.bounds.size.height];         textField.leftView = spacer;         textField.leftViewMode = UITextFieldViewModeAlways;     } }

回答1:

Just ran into the same problem and didn't want to subclass, just had to use :

leftWrapper.userInteractionEnabled = NO;


回答2:

I abandoned this approach. Instead of using an invisible view to offset the text, I opted to subclass UITextField and provide offset CGRects for the bounds of the text within theUITextField. The following SO post was very helpful:

Indent the text in a UITextField



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!