简体   繁体   中英

How to add padding/dynamic edge inset to UIButton based on text size?

I have a button who's title will be changing and I need the button to adjust accordingly; and maintain a certain padding. I've tried playing around with edge inset etc for a while but I have no clue why what I'm trying isn't working. Is there anyway to get the button to dynamically decide/adjust its size so it's always got a certain padding from the text; similar to the ctrl = button in xCode?]

Thanks :)

You can set through storyboard, every button will get same padding Like this . Or in alternate Subclass UIButton and set that class on your desired padding button. Like this:

class Button: UIButton {
  override var intrinsicContentSize: CGSize {
    get {
        let baseSize = super.intrinsicContentSize
        return CGSize(width: baseSize.width + titleEdgeInsets.left + titleEdgeInsets.right,
                      height: baseSize.height + titleEdgeInsets.top + titleEdgeInsets.bottom)
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM