UITextField — Adding UIView for leftView - Can'

2019-05-14 15:21发布

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;
    }
}

2条回答
我命由我不由天
2楼-- · 2019-05-14 15:54

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

查看更多
贼婆χ
3楼-- · 2019-05-14 16:15

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

leftWrapper.userInteractionEnabled = NO;
查看更多
登录 后发表回答