Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indent the text in a UITextField

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.

like image 394
Dyldo42 Avatar asked Sep 27 '11 07:09

Dyldo42


2 Answers

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 
like image 127
adjwilli Avatar answered Oct 07 '22 22:10

adjwilli


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]; 
like image 39
Jano Avatar answered Oct 07 '22 22:10

Jano