Indent the text in a UITextField

Dyldo42 picture Dyldo42 · Sep 27, 2011 · Viewed 51.8k times · Source

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.

Answer

adjwilli picture adjwilli · Jun 6, 2013

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