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