无法使用的UIImageView和的UILabel水平stackView内部时同时满足约束编程
问题描述:
我有以下代码无法使用的UIImageView和的UILabel水平stackView内部时同时满足约束编程
class SecondViewController: UIViewController {
let kFontName = "SourceSansPro-Light"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let firstRowTextLabel = UILabel()
firstRowTextLabel.widthAnchor.constraintEqualToConstant(self.view.frame.width).active = true
firstRowTextLabel.heightAnchor.constraintEqualToConstant(20.0).active = true
firstRowTextLabel.text = "Hi World"
firstRowTextLabel.font = UIFont(name:kFontName, size:24)
// textLabel.textAlignment = .Center
firstRowTextLabel.translatesAutoresizingMaskIntoConstraints = false
let firstRowImageView = UIImageView()
firstRowImageView.heightAnchor.constraintEqualToConstant(60.0).active = true
firstRowImageView.widthAnchor.constraintEqualToConstant(60.0).active = true
firstRowImageView.image = UIImage(named: "settings_black")
firstRowImageView.translatesAutoresizingMaskIntoConstraints = false
let firstRowStackView = UIStackView()
firstRowStackView.axis = UILayoutConstraintAxis.Horizontal
firstRowStackView.distribution = UIStackViewDistribution.FillEqually
firstRowStackView.alignment = UIStackViewAlignment.Center
firstRowStackView.spacing = 25.0
firstRowStackView.addArrangedSubview(firstRowImageView)
firstRowStackView.addArrangedSubview(firstRowTextLabel)
firstRowStackView.translatesAutoresizingMaskIntoConstraints = false
let secondRowLabel = UILabel()
secondRowLabel.widthAnchor.constraintEqualToConstant(self.view.frame.width).active = true
secondRowLabel.heightAnchor.constraintEqualToConstant(20.0).active = true
let stackView = UIStackView()
stackView.axis = UILayoutConstraintAxis.Vertical
stackView.distribution = UIStackViewDistribution.EqualSpacing
stackView.alignment = UIStackViewAlignment.Center
stackView.spacing = 25.0
stackView.addArrangedSubview(firstRowStackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(stackView)
stackView.centerXAnchor.constraintEqualToAnchor(self.view.centerXAnchor).active = true
let constraint = NSLayoutConstraint(
item: stackView,
attribute: .Top,
relatedBy: .Equal,
toItem: topLayoutGuide,
attribute: .Bottom,
multiplier: 1.0,
constant: 50.0
)
self.view.addConstraint(constraint)
}
...
}
当我运行它,我得到以下结果:
这是我正在做的布局,除了我得到的这个事实,我得到了
无法同时满足的约束
消息在我的控制台
当我注释掉以下行:
firstRowStackView.distribution = UIStackViewDistribution.FillEqually
在我的控制台断裂约束错误消失但布局不具备图像和文字中心对齐了,而是我得到这个:
什么是我需要将上面的代码,为了不破坏约束来实现以下布局的最小变化:
答
确定。我只是想出了解决方案。
我改变了以下行:
firstRowTextLabel.widthAnchor.constraintEqualToConstant(self.view.frame.width).active = true
到
firstRowTextLabel.widthAnchor.constraintEqualToConstant(100.0).active = true
和注释掉以下行:
// firstRowStackView.distribution = UIStackViewDistribution.FillEqually
这奏效了我。