2016-04-30 45 views
0

我正在嘗試將實用按鈕添加到UIView。此代碼將與UI標籤一起使用,但是在使用按鈕時,約束會失敗。我該如何做這項工作?謝謝。UIButton約束失敗,但與UILabel一起工作

let homeButton = UIButton(frame: CGRectZero) 
    homeButton.setTitle("Home", forState: .Normal) 
    homeButton.titleLabel!.textAlignment = NSTextAlignment.Center 
    homeButton.titleLabel!.textColor = UIColor.whiteColor() 
    homeButton.titleLabel!.translatesAutoresizingMaskIntoConstraints = false 
    containerView.addSubview(homeButton) 

    let buttonWidthConstraint = NSLayoutConstraint(item: homeButton, attribute: .Width, relatedBy: .Equal, toItem: self.containerView, attribute: .Width, multiplier: 0.5, constant: 0) 
    containerView.addConstraint(buttonWidthConstraint) 
    let buttonHeightConstraint = NSLayoutConstraint(item: homeButton, attribute: .Height, relatedBy: .Equal, toItem: self.containerView, attribute: .Height, multiplier: 0.5,constant: 0) 
    containerView.addConstraint(buttonHeightConstraint) 

    let buttonXConstraint = NSLayoutConstraint(item: homeButton, attribute: .CenterX, relatedBy: .Equal, toItem: self.containerView, attribute: .CenterX, multiplier: 1, constant: 0) 
    let buttonYConstraint = NSLayoutConstraint(item: homeButton, attribute: .CenterY, relatedBy: .Equal, toItem: self.containerView, attribute: .CenterY, multiplier: 1, constant: 0) 
    containerView.addConstraint(buttonXConstraint) 
    containerView.addConstraint(buttonYConstraint) 
+1

使用'homeButton.translatesAutoresizingMaskIntoConstraints = FALSE' –

+0

工程。謝謝 – Clint

回答

0

你應該使用homeButton.translatesAutoresizingMaskIntoConstraints = false代替homeButton.titleLabel!.translatesAutoresizingMaskIntoConstraints = false

因爲你應該禁用自動恢復屏蔽button不適用於按鈕的titleLabel !!!

希望這將有助於:)