subzero subzero - 2 years ago 612
iOS Question

UITextfield leftView/rightView padding on iOS7

The leftView and rightView views of an UITextField on iOS7 are really close to the textfield border.

How may I add some (horizontal) padding to those items?

I tried modifying the frame, but did not work

uint padding = 10;//padding for iOS7
UIImageView * iconImageView = [[UIImageView alloc] initWithImage:iconImage];
iconImageView.frame = CGRectMake(0 + padding, 0, 16, 16);
textField.leftView = iconImageView;

Please, note that I'm not interested in adding padding to the textfield's text, like this Set padding for UITextField with UITextBorderStyleNone

Answer Source

Was just working on this myself and used this solution:

- (CGRect) rightViewRectForBounds:(CGRect)bounds {

    CGRect textRect = [super rightViewRectForBounds:bounds];
    textRect.origin.x -= 10;
    return textRect;

This will move the image over from the right by 10 instead of having the image squeezed up against the edge in iOS 7.

Additionally, this was in a subclass of UITextField, which can be created by:

  1. Create a new file that's a subclass of UITextField instead of the default NSObject
  2. Add a new method named - (id)initWithCoder:(NSCoder*)coder to set the image

    - (id)initWithCoder:(NSCoder*)coder {
        self = [super initWithCoder:coder];
        if (self) {
            self.clipsToBounds = YES;
            [self setRightViewMode:UITextFieldViewModeUnlessEditing];
            self.leftView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"textfield_edit_icon.png"]];
        return self;
  3. You may have to import #import <QuartzCore/QuartzCore.h>

  4. Add the rightViewRectForBounds method above

  5. In Interface Builder, click on the TextField you would like to subclass and change the class attribute to the name of this new subclass

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download