
Reading Time: 2 minutes
In this short post I want to show you how you can set padding for UITextField on iOS as this feature is not available out of the box.
On iOS there are couple of controls for displaying or entering text, like UILabel, UITextField and UITextView. In case case you need to gather user input there are two options – UITextField and UITextView. Which one to use, you may wonder? If you need multiple lines of input use UITextView and if there is only one line of text (for example username or password) use UITextField.
As Apple says in official documentation UITextField is an object that displays an editable text area in your interface.
So basically UITextField is a component that is used to get text-based input from the user. For this user uses onscreen keyboard which can be configured for different types of input like emails, numbers, password, plain text and so on.
But in this post I won’t talk about using and configuring UITextField, as I presume you’re already familiar with it. As this post title says I want to show you how you can set padding on UITextField because there is no native support for this functionality (you can’t set padding on UITextField by accessing some of UITextField properties).
Set padding for UITextField on iOS with Swift
So how can you set padding for UITextField on iOS with Swift? Simply by extending or subclassing UITextField and writing your own code which will set padding on UITextField.
extension UITextField { func setPadding(left: CGFloat, right: CGFloat? = nil) { setLeftPadding(left) if let rightPadding = right { setRightPadding(rightPadding) } } private func setLeftPadding(_ padding: CGFloat) { let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: padding, height: self.frame.size.height)) self.leftView = paddingView self.leftViewMode = .always } private func setRightPadding(_ padding: CGFloat) { let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: padding, height: self.frame.size.height)) self.rightView = paddingView self.rightViewMode = .always } }
Now you can set padding on any UITextField in your project simply by calling setPadding function.
let padding: CGFloat = 10.0 textfield?.setPadding(left: padding, right: padding)
Wrap up
Pretty simple, right? As you see although there is no native support for setting padding for UITextField solution for this problem is not complicated at all. I hope this article was helpful and useful and that you learned something. If it was please share this article with your friends. And if you have any questions or problems leave me a comment or send an email.