我正在学习自动布局锚点并试图以编程方式实现这个简单的事情
这是我的代码
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
let view1 = UIView()
view1.backgroundColor = .brown
blueView.addSubview(view1)
view1.translatesAutoresizingMaskIntoConstraints = false
view1.topAnchor.constraint(equalTo: blueView.topAnchor, constant:10).isActive = true
view1.bottomAnchor.constraint(equalTo: blueView.bottomAnchor, constant:10).isActive = true
view1.leadingAnchor.constraint(equalTo: blueView.leadingAnchor, constant:10).isActive = true
view1.trailingAnchor.constraint(equalTo: blueView.trailingAnchor, constant:10).isActive = true
view1.heightAnchor.constraint(equalToConstant: 80).isActive = true
view1.widthAnchor.constraint(equalToConstant: 80).isActive = true
}
这就是我得到的
出了什么问题?
答案 0 :(得分:1)
出了什么问题?
我看到三类问题:
heightAnchor
和widthAnchor
约束,以便isActive = true
view1
不能超过100分和从superview 和底部锚点> 284点,同时全部。以下是这三个问题的一种可能解决方案:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
let view1 = UIView()
view1.backgroundColor = .brown
view.addSubview(view1)
view1.translatesAutoresizingMaskIntoConstraints = false
view1.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
view1.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
view1.heightAnchor.constraint(equalToConstant: 100.0).isActive = true
view1.widthAnchor.constraint(equalToConstant: 100.0).isActive = true
}
这里,我们将view1
的X和Y中心设置为等于超视图的X和Y中心,将view1
的高度和宽度定义为常量,并设置所有相关约束活跃。
您可以在Auto Layout Guide中找到其他解决方案。
答案 1 :(得分:0)
尝试这样做:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
let view1 = UIView()
view1.backgroundColor = .brown
view.addSubview(view1)
view1.translatesAutoresizingMaskIntoConstraints = false
//Constraints
let centerXConstraint = view1.centerXAnchor.constraint(equalTo: self.view.centerXAnchor, constant: 0)
let centerYConstraint = view1.centerYAnchor.constraint(equalTo: self.view.centerYAnchor, constant: 0)
let widthConstraint = view1.widthAnchor.constraint(equalToConstant: 100)
let heightConstraint = view1.heightAnchor.constraint(equalToConstant: 100)
//Apply constraints
constraintToApply.append(centerXConstraint)
constraintToApply.append(centerYConstraint)
constraintToApply.append(widthConstraint)
constraintToApply.append(heightConstraint)
}
并添加以下代码:
override func viewDidAppear(_ animated: Bool) {
// Apply Constraints
NSLayoutConstraint.activate(constraintToApply)
self.view.layoutIfNeeded()
}
希望这可以帮到你。
答案 2 :(得分:0)
您为每个约束添加+10点。
view1.topAnchor.constraint(equalTo: blueView.topAnchor, constant:10).isActive = true
这意味着"将view1的顶部锚点设置为blueView的顶部锚点加上10"
只需删除constant:10
view1.topAnchor.constraint(equalTo: blueView.topAnchor).isActive = true
如果您设置了顶部,底部,左侧,前导和尾随锚,您不应设置高度和宽度。宽度和高度将根据这4个锚点计算。所以,你应该删除
view1.heightAnchor.constraint(equalToConstant: 80).isActive = true
view1.widthAnchor.constraint(equalToConstant: 80).isActive = true