我的ViewController中有以下代码
let imageView = UIImageView()
imageView.backgroundColor = UIColor.blueColor()
imageView.heightAnchor.constraintEqualToConstant(120.0).active = true
imageView.widthAnchor.constraintEqualToConstant(120.0).active = true
imageView.image = UIImage(named: "buttonFollowCheckGreen")
let textLabel = UILabel()
textLabel.widthAnchor.constraintEqualToConstant(self.view.frame.width).active = true
textLabel.heightAnchor.constraintEqualToConstant(20.0).active = true
textLabel.text = "Hi World"
textLabel.font = UIFont(name:kFontName, size:24)
textLabel.textAlignment = .Center
let stackView = UIStackView()
stackView.axis = UILayoutConstraintAxis.Vertical
// stackView.distribution = UIStackViewDistribution.EqualSpacing
// stackView.alignment = UIStackViewAlignment.Center
stackView.spacing = 16.0
stackView.addArrangedSubview(imageView)
stackView.addArrangedSubview(textLabel)
stackView.translatesAutoresizingMaskIntoConstraints = false;
self.view.addSubview(stackView)
stackView.centerXAnchor.constraintEqualToAnchor(self.view.centerXAnchor).active = true
stackView.centerYAnchor.constraintEqualToAnchor(self.view.centerYAnchor).active = true
我想让它呈现如下:
完成此操作的上述代码的最小更改是什么。我希望stackView上的一个属性可以将它与顶部对齐。
答案 0 :(得分:1)
将最后两行替换为:
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: 0.0
)
view.addConstraint(constraint)
此外,您正在使用自动布局的代码中创建视图,因此您需要通过添加以下两行来关闭自动调整遮罩
imageView.translatesAutoresizingMaskIntoConstraints = false
textLabel.translatesAutoresizingMaskIntoConstraints = false
你的堆栈视图中的视图仍然存在一些冲突,但这不是问题的一部分,所以我会留给你尝试修复。