Skip to main content

How to add padding to UITextField placeholder in Swift

· 2 min read
Full Stack Developer
Last updated on August 15, 2018

While working on our newly launched Dashboard iOS app template, we had to figure out how to add a padding to the placeholder of a UITextField control. It turned out there’s no native support for this design tweak, so we had to create our own subclass of UITextField.

Since many iOS developers will run into this at some point, we thought it’d be a good idea to share our workaround for how we added spacing to the placeholder of a UITextField control in Swift. Here’s the Swift source code of the UITextField subclass:

Mega Bundle Sale is ON! Get ALL of our iOS App codebases at 90% OFF discount 🔥

Get the Mega Bundle
import UIKit
class ATCTextField: UITextField {
let padding = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 5)
override open func textRect(forBounds bounds: CGRect) -> CGRect {
return UIEdgeInsetsInsetRect(bounds, padding)
}
override open func placeholderRect(forBounds bounds: CGRect) -> CGRect {
return UIEdgeInsetsInsetRect(bounds, padding)
}
override open func editingRect(forBounds bounds: CGRect) -> CGRect {
return UIEdgeInsetsInsetRect(bounds, padding)
}
}

Of course, the architecture is not really ideal since the padding is not modularized. Ideally, you should create your own constructor and inject the padding as a CGFloat parameter. But for demonstration purposes, this should do it. We did not need a more generic approach for this UITextField placeholder padding, because we’re only using it in one of our app designs for Onboarding Screens (for both login and registration UI screens).

This is usually our approach when it comes to code architecture in general – Do the simple thing first and as the components start being used by multiple consumers (designs, templates, objects), refine the architecture to make the API more scalable.

PS: If you’re using Interface Builder (with .xibs), don’t forget to update the name of the class to ATCTextField for all the UITextField components you want to add padding to.

Looking for a custom mobile application?

Our team of expert mobile developers can help you build a custom mobile app that meets your specific needs.

Get in Touch