iOS: UIButton resize according to text length

后端 未结 14 833
你的背包
你的背包 2020-11-29 17:28

In interface builder, holding Command + = will resize a button to fit its text. I was wondering if this was possible to do programmatically before the

14条回答
  •  遥遥无期
    2020-11-29 18:05

    Swift:

    The important thing here is when will you call the .sizeToFit() , it should be after setting the text to display so it can read the size needed, if you later update text, then call it again.

    var button = UIButton()
    button.setTitle("Length of this text determines size", forState: UIControlState.Normal)
    button.sizeToFit()
    self.view.addSubview(button)
    

提交回复
热议问题