Mega Bundle SALE is ON! Get ALL of our amazing iOS app codebases at 95% OFF discount 🔥

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:

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.


Leave a Reply

Your email address will not be published. Required fields are marked *

Shopping Cart