Learn how to enhance the look of Textfields with paddings in Swift

Lawrence Tan
NYC Design
Published in
2 min readFeb 17, 2017

In our modern days design of mobile apps, it is essential for us to add padding so that the fields look more clean and sleek. So how do we add padding in Swift 3?

From this :

To this :

Its very simple, just one line of code! Normally I will create a standard custom class of such textfield, so that I can reuse it anytime across storyboards in the project.

class CustomSearchTextField: UITextField {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}

override func textRect(forBounds bounds: CGRect) -> CGRect {
return UIEdgeInsetsInsetRect(bounds,
UIEdgeInsetsMake(0, 15, 0, 15))
}
override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
return UIEdgeInsetsInsetRect(bounds,
UIEdgeInsetsMake(0, 15, 0, 15))
}
}

https://gist.github.com/lawreyios/5d13bc80d999634e37401e3bc3e5bd23

So the main engine that drives this padding isUIEdgeInsetsInsetRect(bounds, UIEdgeInsetsMake(0, 15, 0, 15))

There you have it! Adjust the right and left, or even top and bottom according to your likings!

Before you go…

If you enjoyed this post, you will love Lawrey Swifty Weekly. It’s my FREE weekly digest of the best iOS-related nuggests and stuffs about life, productivity and self improvement. Subscribe here. Join readers around the world to be more swifty!

--

--

Lawrence Tan
NYC Design

Googler. Loves God, Loves my wife, Loves my Family & Corgis.