How to remove the top and bottom padding of UIButton, when create it using auto layout? How to remove the top and bottom padding of UIButton, when create it using auto layout? ios ios

How to remove the top and bottom padding of UIButton, when create it using auto layout?


After some experimentation, it appears that if you try and set contentEdgeInsets to all zeros, the default insets are used. However, if you set them to nearly zero, it works:

button.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0.01, bottom: 0.01, right: 0)

It also appears that the values get floor'd, so you won't actually get fractional padding.


Updated for Swift 5

If you are wanting the button to size to its titleLabel's contents, I found that the only way to do so is by subclassing UIButton and overriding intrinsicContentSize. Hope this works for you!

class CustomButton: UIButton {    override var intrinsicContentSize: CGSize {        return titleLabel?.intrinsicContentSize ?? super.intrinsicContentSize    }}

If you need to use titleEdgeInsets, you can update your UIButton subclass like this:

class CustomButton: UIButton {    override var titleEdgeInsets: UIEdgeInsets {        didSet {            invalidateIntrinsicContentSize()        }    }    override var intrinsicContentSize: CGSize {        var sizeWithInsets = titleLabel?.intrinsicContentSize ?? super.intrinsicContentSize        sizeWithInsets.width += titleEdgeInsets.left + titleEdgeInsets.right        sizeWithInsets.height += titleEdgeInsets.top + titleEdgeInsets.bottom        return sizeWithInsets    }}


CGFloat has a leastNormalMagnitude value that works nicely for this unfortunate UIKit hack.

someButton.titleEdgeInsets = UIEdgeInsets(top: .leastNormalMagnitude, left: .leastNormalMagnitude, bottom: .leastNormalMagnitude, right: .leastNormalMagnitude)someButton.contentEdgeInsets = UIEdgeInsets(top: .leastNormalMagnitude, left: .leastNormalMagnitude, bottom: .leastNormalMagnitude, right: .leastNormalMagnitude)

Zeroing out title-edge insets alone will only zero out the leading and trailing insets. Therefore, we have to also zero out content-edge insets to zero out the top and bottom.

And for convenience:

extension UIEdgeInsets {    init(repeating value: CGFloat) {        self.init(top: value, left: value, bottom: value, right: value)    }    static let leastNormalMagnitude = UIEdgeInsets(repeating: CGFloat.leastNormalMagnitude)}someButton.titleEdgeInsets = .leastNormalMagnitudesomeButton.contentEdgeInsets = .leastNormalMagnitude