将不透明的子视图添加到UITextField

时间:2013-02-19 15:40:21

标签: ios objective-c uiview uitextfield opacity

我有一个UITextField的子类,我正在尝试为它添加一个不透明的子视图。但是,当我输入UITextField时,它显示为透明,我可以看到视图后面的文字。如何使视图完全不透明?以下是进入子类并添加视图的代码。

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
       _dropdownIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ab- dropdown-on"]];     
        dropdownIcon.backgroundColor = [UIColor blackColor];
       _dropdownIcon.frame = CGRectMake(self.frame.size.width-DROPDOWN_ICON_SIZE,0,DROPDOWN_ICON_SIZE,DROPDOWN_ICON_SIZE);
       [self addSubview:_dropdownIcon];
   }
    return self;
}

This is what I get

1 个答案:

答案 0 :(得分:2)

您的子类需要覆盖-textRectForBounds:方法以返回您希望文本绘制的实际区域,例如

- (CGRect)textRectForBounds:(CGRect)bounds
{
    CGRect textRect = [super textRectForBounds:bounds];
    textRect.size.width -= 30; // or however wide your control is—play with this value
    return textRect;
}

您所看到的不是图标不透明 - 文本只是在其上绘制,因为文本字段不“知道”图标在那里。

您还可以查看rightView属性和相关的-rightViewRectForBounds:方法,但如果您希望文本字段自动显示和隐藏附件视图,则这些方法非常有用。

相关问题