可以使用锚点以编程方式向视图添加UIButton

时间:2019-05-14 03:19:15

标签: ios swift uibutton ios-autolayout

我正在尝试向视图添加UIButton。我可以这样做,但是我必须使用UIButton.frame。例如

startBtn.frame = CGRect(x: 10.0, y: 10.0, width: 300.0, height: 100.0)

我需要使用自动布局锚,但是这些锚似乎不适用于UIButton。

我如何做到这一点?

class HomeView: UIViewController {

    var startButtonView : UIButton = {
        let startBtn = UIButton(type: UIButton.ButtonType.custom) as UIButton
        let startBtnImage = UIImage(named: "StartButton") as UIImage?
        let startBtnText = NSLocalizedString("Start Test", comment: "")
        let btnTitleColor = UIColor(red: 62.0/255, green: 130.0/255, blue: 209.0/255, alpha: 1.0)
        startBtn.setTitleColor(btnTitleColor, for: [])
        startBtn.setTitle(startBtnText, for: [])
        startBtn.setBackgroundImage(startBtnImage, for: [])
        startBtn.frame = CGRect(x: 10.0, y: 10.0, width: 300.0, height: 100.0)
        return startBtn
    }()

override func viewDidLoad() {
        super.viewDidLoad()
        setStartBtn();
}

    func setStartBtn() {
        view.addSubview(startButtonView)
        startButtonView.addTarget(self, action: #selector(self.clickStart(_:)), for: .touchUpInside) //Add a target and action of the start buton
        startButtonView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor, constant: 150).isActive = true
        startButtonView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
        startButtonView.widthAnchor.constraint(equalToConstant: 350).isActive = true
        startButtonView.heightAnchor.constraint(equalToConstant: 100).isActive = true
    }

}

0 个答案:

没有答案