UITextField文本重叠清除按钮

时间:2011-12-02 05:47:46

标签: objective-c ios uitextfield

我在这样的视图中添加了一个文本字段:

UITextField* tf_email = [[UITextField alloc] initWithFrame:CGRectMake((320-btnImage1.size.width)/2, 170, 175, 35)];
    [tf_email setBackgroundColor:[UIColor clearColor]];
    [tf_email setBorderStyle:UITextBorderStyleRoundedRect];
    [tf_email setClearButtonMode:UITextFieldViewModeWhileEditing];
    [tf_email setReturnKeyType:UIReturnKeyDone];
    [tf_email setAutocapitalizationType:UITextAutocapitalizationTypeNone];
    [tf_email setEnablesReturnKeyAutomatically:NO];
    [tf_email setDelegate:self];    
    [tf_email setOpaque:YES];
    tf_email.tag=1;
    tf_email.font = TTSTYLEVAR(font);
    tf_email.layer.cornerRadius = 10;
    tf_email.keyboardType = UIKeyboardTypeEmailAddress;
    [tf_email setAutocorrectionType:UITextAutocorrectionTypeNo];
    tf_email.placeholder = @"your@email.com";
    [self.view addSubview:tf_email];

当我在此字段中输入长文本时,文本和清除按钮重叠。有没有人知道如何解决这个问题?

4 个答案:

答案 0 :(得分:12)

创建UITextField的子类并覆盖下面给出的方法

/*< Place holder position >*/
- (CGRect)textRectForBounds:(CGRect)bounds {

    bounds.size.width = bounds.size.width - 20.0f;
    return bounds;
}

/*< Text Posiotion >*/
- (CGRect)editingRectForBounds:(CGRect)bounds {

    bounds.size.width = bounds.size.width - 20.0f;
    return bounds;
}

干杯!!!

答案 1 :(得分:3)

我想出了问题所在。在另一个文件中,我有一个为UITextField定义的类别。此类别指定文本区域非常靠近左右边框。这导致了重叠。

获得的经验:在定义类别时,我们应该使用单独的文件,以便可以轻松检测到修改。

答案 2 :(得分:3)

@Augustine P A, I think a better approach is to call the super and modify the result like this:

-(CGRect) textRectForBounds:(CGRect)bounds
{
    CGRect rect = [super textRectForBounds:bounds];
    rect.size.width = rect.size.width - 20.0f;
    return rect;
}

-(CGRect) editingRectForBounds:(CGRect)bounds
{
    CGRect rect = [super editingRectForBounds:bounds];
    rect.size.width = rect.size.width - 20.0f;
    return rect;
}

答案 3 :(得分:1)

[button bringSubviewToFront:self.view];

添加文字字段后..