I wanted to use a custom background for my UITextFields
. This works fine except for the fact that I have to use UITextBorderStyleNone
to make it look pretty. This forces the text to stick to the left without any padding.
Can I set a padding manually so that it looks similar to UITextBorderStyleRoundedRect
except for using my custom background image?
Here's how to achieve this in SWIFT
Resource
Edit: Still works in iOS 11.3.1
In iOS 6
myTextField.leftView = paddingView;
is causing issueThis solves the problem
For right aligned text field use
CATransform3DMakeTranslation(-5, 0, 0)
as mention by latenitecoder in commentsSet padding for UITextField with UITextBorderStyleNone: Swift
Based on @Evil Trout's most voted answer I created a custom method in my ViewController class, like shown bellow:
Now I can call that method inside (viewDidLoad method) and send any of my TextFields to that method and add padding for both right and left, and give text and background colors by writing just one line of code, as follows:
This Worked perfectly on iOS 7! I know that adding too much Views might make this a bit heavier class to be loaded. But when concerned about the difficulty in other solutions, I found myself more biased to this method and more flexible with using this way. ;)
Thanks for the Hack "Evil Trout"! (bow)
I thought I should update this answer's code snippet with Swift:
Since Swift allow us to write extensions for the existing classes, let's write it in that way.
Usage:
Hope this would be helpful to somebody else out there!
Cheers!
you can use category. set padding to left and right
UITextField+Padding.h
UITextField+Padding.m
you can set padding like this self.phoneNumTF.paddingValue=10.f; or self.phoneNumTF.leftPadding=10.f;
@Evil trout's answer is great. I have been using this approach for quite a some time now. The only thing it lacks is "dealing with numerous text fields". I tried other approaches but does not seem to work.
Subclassing UITextField just to add a padding didn't make any sense to me. So, I iterated over all UITextFields to add the padding.
You can't set padding. Instead have a
UIView
which has your background image and theUITextField
inside of it. Set theUITextField
width asUIViewWidth-(paddingSize x 2)
and the height similarly and then set it at pointpaddingSize,paddingSize
.