My question is as simple as the title, but here's a little more:
I have a UITextField, on which I've set the background image. The problem is that the text hugs so closely to it's edge, which is also the edge of the image. I want my text field to look like Apple's, with a bit of horizontal space between the background image and where the text starts.
This is the quickest way I've found without doing any subclasses:
UIView *spacerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)]; [textfield setLeftViewMode:UITextFieldViewModeAlways]; [textfield setLeftView:spacerView];
In Swift:
let spacerView = UIView(frame:CGRect(x:0, y:0, width:10, height:10)) textField.leftViewMode = UITextFieldViewMode.Always textField.leftView = spacerView
You have to subclass and override textRectForBounds: and editingRectForBounds:. Here is a UITextfield subclass with custom background and vertical and horizontal padding:
@interface MyUITextField : UITextField @property (nonatomic, assign) float verticalPadding; @property (nonatomic, assign) float horizontalPadding; @end #import "MyUITextField.h" @implementation MyUITextField @synthesize horizontalPadding, verticalPadding; - (CGRect)textRectForBounds:(CGRect)bounds { return CGRectMake(bounds.origin.x + horizontalPadding, bounds.origin.y + verticalPadding, bounds.size.width - horizontalPadding*2, bounds.size.height - verticalPadding*2); } - (CGRect)editingRectForBounds:(CGRect)bounds { return [self textRectForBounds:bounds]; } @end
Usage:
UIImage *bg = [UIImage imageNamed:@"textfield.png"]; CGRect rect = CGRectMake(0, 0, bg.size.width, bg.size.height); MyUITextField *textfield = [[[MyUITextField alloc] initWithFrame:rect] autorelease]; textfield.verticalPadding = 10; textfield.horizontalPadding = 10; [textfield setBackground:bg]; [textfield setBorderStyle:UITextBorderStyleNone]; [self.view addSubview:textfield];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With