UITextField - 为leftView添加UIView - 无法获得Focus

时间:2012-05-30 14:57:28

标签: objective-c ios interface-builder uitextfield

我的应用程序中的UITextFields定义了占位符文本(在Interface Builder中),当我点击占位符文本占用的区域时,我无法使这些字段获得焦点(即显示键盘并允许编辑)。如果我点击位于占位符文本之外的区域中的文本字段(尽管仍然在文本文本本身的范围内),它会正常运行(即键盘弹出,我可以编辑文本字段的内容)。我该如何解决这个问题?

感谢。

编辑1

好的,我想我已经知道了。我还设置了这些UITextFields的“leftView”属性的空白视图。如果我删除它,你可以触摸占位符文本区域中的UITextFields,它会按预期做出反应;我需要这个视图为leftView。如果您将此间隔视图的背景颜色更改为红色,您可以看到它根本不会妨碍,所以我不知道出了什么问题。

为什么此代码会导致此问题?

感谢。

+(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 个答案:

答案 0 :(得分:7)

刚遇到同样的问题并且不想继承子类,只需要使用:

leftWrapper.userInteractionEnabled = NO;

答案 1 :(得分:1)

我放弃了这种方法。我没有使用不可见的视图来偏移文本,而是选择子类UITextField,并为UITextField中的文本边界提供偏移CGRect。以下SO帖子非常有用:

Indent the text in a UITextField