UITextField - 为leftView添加UIView - 无法获得Focus [英] UITextField -- Adding UIView for leftView - Can't get Focus

查看:101
本文介绍了UITextField - 为leftView添加UIView - 无法获得Focus的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

谢谢。

编辑1

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

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?

谢谢。

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


推荐答案

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

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:

缩进UITextField中的文本

这篇关于UITextField - 为leftView添加UIView - 无法获得Focus的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆