UIButton add padding

Ngchiwa Ng
2 min readJan 26, 2018

--

First all, I want to create a button that use auto layout and have padding on leading and trailing with title

if a create a button that only 2 constrain(vertical, horizontal constraint depend on super view), the size will auto adjust by title of button,.

for example:

build in simulator , there are no any padding

now you can create a custom class to override intrinsicContentSize , for example create AutoAddPaddingButton class

import Foundationimport UIKitclass AutoAddPaddingButtton : UIButton{
override var intrinsicContentSize: CGSize {
get {
let baseSize = super.intrinsicContentSize
return CGSize(width: baseSize.width + 20,//ex: padding 20
height: baseSize.height)
}
}}

and set Custom Class in xib/storyboard

result:

great !

--

--

Ngchiwa Ng
Ngchiwa Ng

Written by Ngchiwa Ng

Backend/iOS Engineer, rock the world

No responses yet