【问题标题】:UIButton Constraint Failure, but works with UILabelUIButton 约束失败,但适用于 UILabel
【发布时间】:2016-04-30 06:29:57
【问题描述】:

我正在尝试将按钮实用地添加到 UIView。此代码将与 UI 标签一起使用,但在将其与按钮一起使用时,约束会失败。我怎样才能使这项工作?谢谢。

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)

【问题讨论】:

  • 使用homeButton.translatesAutoresizingMaskIntoConstraints = false
  • 那行得通。谢谢

标签: ios xcode swift uibutton nslayoutconstraint


【解决方案1】:

您应该使用homeButton.translatesAutoresizingMaskIntoConstraints = false 而不是homeButton.titleLabel!.translatesAutoresizingMaskIntoConstraints = false

因为您应该禁用 button 的自动调整掩码而不是按钮的 titleLabel !!!

希望这会有所帮助:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-01
    • 2015-09-12
    • 2018-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多