NickDK
NickDK

Reputation: 1009

Add opaque subview to UITextField

I have a subclass of UITextField and I'm trying ot add an opaque subview to it. However, when I type in the UITextField, it appears transparent and I can see the text behind the view. How can I make the view fully opaque? Here is the code that inits the subclass and adds the view.

- (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

Upvotes: 0

Views: 1193

Answers (1)

Noah Witherspoon
Noah Witherspoon

Reputation: 57139

Your subclass needs to override the -textRectForBounds: method to return the actual area you want text to draw in, e.g.

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

What you’re seeing is not the icon being non-opaque—the text is just being drawn over it, because the text field doesn’t “know” the icon is there.

You might also look into the rightView property and the related -rightViewRectForBounds: method, though those are mostly useful if you want the text field to automatically show and hide your accessory view.

Upvotes: 2

Related Questions