Incidentally, you can also do something like the following, if you want to control the inset of just one side. This particular example of adjusting only the left inset comes in handy if you place an image on top of the UITextField but you want it to appear to the user to be within the text field:
A good approach to add padding to UITextField is to subclass UITextField and add an edgeInsets property. You then set the edgeInsets and the UITextField will be drawn accordingly. This will also function correctly with a custom leftView or rightView set.
Overriding -textRectForBounds: will only change the inset of the placeholder text. To change the inset of the editable text, you need to also override -editingRectForBounds:
// placeholder position
- (CGRect)textRectForBounds:(CGRect)bounds {
return CGRectInset(bounds, 10, 10);
}
// text position
- (CGRect)editingRectForBounds:(CGRect)bounds {
return CGRectInset(bounds, 10, 10);
}
Tested with iOS 7 and iOS 8. Both working. Still there might be the chance of Apple modifying the UITextField's layer hierarchy screwing up things badly.
Here's a comprehensive Swift answer that includes a leftView (custom icon) and a custom clear button, both set in Interface Builder with customizable insets.
Here is the same subclassed UITextField written in Swift 3. It is quite different from prior versions of Swift, as you'll see:
Incidentally, you can also do something like the following, if you want to control the inset of just one side. This particular example of adjusting only the left inset comes in handy if you place an image on top of the UITextField but you want it to appear to the user to be within the text field:
It's the quickest way I've found without doing any subclasses:
In Swift:
A good approach to add padding to UITextField is to subclass UITextField and add an edgeInsets property. You then set the edgeInsets and the UITextField will be drawn accordingly. This will also function correctly with a custom leftView or rightView set.
OSTextField.h
OSTextField.m
Overriding
-textRectForBounds:
will only change the inset of the placeholder text. To change the inset of the editable text, you need to also override-editingRectForBounds:
To throw in another solution that has no need for subclassing:
Tested with iOS 7 and iOS 8. Both working. Still there might be the chance of Apple modifying the UITextField's layer hierarchy screwing up things badly.
Here's a comprehensive Swift answer that includes a leftView (custom icon) and a custom clear button, both set in Interface Builder with customizable insets.