我有一个包含两个标签(nameLabel和nicknameLabel)的stackview。我希望两个标签的高度像第一张图片一样保持恒定,但我也希望stackview的位置距其父视图(masterView)顶部30像素。但是,当我为堆栈视图设置topAnchor约束时,当它们应该像第一张图片一样保持恒定时,它将调整按钮的高度。谁能解释这是为什么以及我如何解决此问题?
这是我带有stackview的代码:
class MasterDetailController: UIViewController {
let masterView: UIView = {
var view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = UIColor.purple
return view
}()
var labelStackView = UIStackView()
var nameLabel = UILabel()
var nicknameLabel = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(masterView)
masterView.addSubview(labelStackView)
labelStackView.translatesAutoresizingMaskIntoConstraints = false
labelStackView.axis = .vertical
labelStackView.distribution = .fill
labelStackView.alignment = .center
labelStackView.spacing = 20
labelStackView.topAnchor.constraint(equalTo: masterView.topAnchor, constant: 30).isActive = true
labelStackView.heightAnchor.constraint(equalToConstant: 130).isActive = true
labelStackView.centerXAnchor.constraint(equalTo: masterView.centerXAnchor).isActive = true
labelStackView.centerYAnchor.constraint(equalTo: masterView.centerYAnchor).isActive = true
masterView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
masterView.heightAnchor.constraint(equalTo: view.heightAnchor).isActive = true
masterView.center = view.center
labelStackView.addArrangedSubview(nameLabel)
labelStackView.addArrangedSubview(nicknameLabel)
setupLayout()
}
func setupLayout() {
nameLabel.translatesAutoresizingMaskIntoConstraints = false
nicknameLabel.translatesAutoresizingMaskIntoConstraints = false
nameLabel.widthAnchor.constraint(equalTo: masterView.widthAnchor, multiplier: 0.75).isActive = true
nameLabel.heightAnchor.constraint(equalToConstant: 80).isActive = true
nameLabel.centerXAnchor.constraint(equalTo: masterView.centerXAnchor).isActive = true
nameLabel.backgroundColor = UIColor.orange
nameLabel.textAlignment = .center
nameLabel.font = UIFont(name: "AvenirNext-Regular", size: 30)
nicknameLabel.widthAnchor.constraint(equalTo: nameLabel.widthAnchor, multiplier: 0.7).isActive = true
nicknameLabel.heightAnchor.constraint(equalToConstant: 60).isActive = true
nicknameLabel.font = UIFont(name: "AvenirNext-Regular", size: 15)
nicknameLabel.textAlignment = .center
nicknameLabel.backgroundColor = UIColor.cyan
}
}
我的目标是使按钮成为第一张图片的大小,但要像第二张图片一样固定在视图的顶部。