UITextfield leftView/rightView padding on iOS7
A much simpler solution, which takes advantage of contentMode
:
arrow = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"down_arrow"]]; arrow.frame = CGRectMake(0.0, 0.0, arrow.image.size.width+10.0, arrow.image.size.height); arrow.contentMode = UIViewContentModeCenter; textField.rightView = arrow; textField.rightViewMode = UITextFieldViewModeAlways;
In Swift 3,
let arrow = UIImageView(image: UIImage(named: "arrowDrop")) if let size = arrow.image?.size { arrow.frame = CGRect(x: 0.0, y: 0.0, width: size.width + 10.0, height: size.height) } arrow.contentMode = UIViewContentMode.center self.textField.rightView = arrow self.textField.rightViewMode = UITextFieldViewMode.always
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:
- Create a new file that's a subclass of
UITextField
instead of the defaultNSObject
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;}
You may have to import
#import <QuartzCore/QuartzCore.h>
Add the
rightViewRectForBounds
method aboveIn Interface Builder, click on the TextField you would like to subclass and change the class attribute to the name of this new subclass
Easiest way is add a UIView to leftView/righView and add an ImageView to UIView , adjust the origin of ImageView inside UIView anywhere you like , this worked for me like a charm. It needs only few lines of code
UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 5, 26, 26)];imgView.image = [UIImage imageNamed:@"img.png"];UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 32, 32)];[paddingView addSubview:imgView];[txtField setLeftViewMode:UITextFieldViewModeAlways];[txtField setLeftView:paddingView];