iOS: UIButton resize according to text length

后端 未结 14 913
你的背包
你的背包 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条回答
  •  旧时难觅i
    2020-11-29 18:02

    To be honest I think that it's really shame that there is no simple checkbox in storyboard to say that you want to resize buttons to accommodate the text. Well... whatever.

    Here is the simplest solution using storyboard.

    1. Place UIView and put constraints for it. Example:
    2. Place UILabel inside UIView. Set constraints to attach it to edges of UIView.

    3. Place your UIButton inside UIView. Set the same constraints to attach it to the edges of UIView.

    4. Set 0 for UILabel's number of lines.

    5. Set up the outlets.

        @IBOutlet var button: UIButton!
        @IBOutlet var textOnTheButton: UILabel!
    
    1. Get some long, long, long title.
    
        let someTitle = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
    
    1. On viewDidLoad set the title both for UILabel and UIButton.
    
        override func viewDidLoad() {
            super.viewDidLoad()
            textOnTheButton.text = someTitle
            button.setTitle(someTitle, for: .normal)
            button.titleLabel?.numberOfLines = 0
        }
    
    1. Run it to make sure that button is resized and can be pressed.

提交回复
热议问题