gpt4 book ai didi

ios - UIButton 约束失败,但适用于 UILabel

转载 作者:行者123 更新时间:2023-11-30 13:27:44 25 4
gpt4 key购买 nike

我正在尝试向 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而不是homeButton.titleLabel!.translatesAutoresizingMaskIntoConstraints = false

因为您应该为button而不是按钮的titleLabel禁用autoresizingmask!

希望这会有所帮助:)

关于ios - UIButton 约束失败,但适用于 UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36951578/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com