Multiline UIButton and autolayout

后端 未结 16 1494
无人共我
无人共我 2020-12-03 13:08

I have created a view controller that looks like this:

\"enter

I want the two

16条回答
  •  再見小時候
    2020-12-03 13:47

    //Swift 4 - Create Dynamic Button MultiLine Dynamic
    
    class ViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
             /// Add DemoButton 1
            let demoButton1 = buildButton("Demo 1")
            //demoButton1.addTarget(self, action: #selector(ViewController.onDemo1Tapped), for: .touchUpInside)
            view.addSubview(demoButton1)
    
            view.addConstraint(NSLayoutConstraint(item: demoButton1, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: 0))
            view.addConstraint(NSLayoutConstraint(item: demoButton1, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1, constant: -180))
    
        }
    
        func buildButton(_ title: String) -> UIButton {
            let button = UIButton(type: .system)
            button.backgroundColor = UIColor(red: 80/255, green: 70/255, blue: 66/255, alpha: 1.0)
    
            //--------------------------
            //to make the button multiline
            //button.titleLabel!.lineBreakMode = .byWordWrapping
            button.titleLabel?.textAlignment = .center
            button.titleLabel?.numberOfLines = 0
            //button.titleLabel?.adjustsFontSizeToFitWidth = true
            //button.sizeToFit()
            button.titleLabel?.preferredMaxLayoutWidth = self.view.bounds.width//200
            button.layer.borderWidth = 2
            let height = NSLayoutConstraint(item: button,
                                            attribute: .height,
                                            relatedBy: .equal,
                                            toItem: button.titleLabel,
                                            attribute: .height,
                                            multiplier: 1,
                                            constant: 0)
            button.addConstraint(height)
            //--------------------------
    
            button.setTitle(title, for: UIControlState())
            button.layer.cornerRadius = 4.0
            button.setTitleColor(UIColor(red: 233/255, green: 205/255, blue: 193/255, alpha: 1.0), for: UIControlState())
            button.translatesAutoresizingMaskIntoConstraints = false
            return button
        }
    }
    

提交回复
热议问题