我创建了一个简单的UIView,其中心包含一个红色框(UIImage)。当所有约束都是常量时,代码工作正常。但是,如果我将高度约束替换为使得框的高度为视图高度的一半,则框会消失。
我认为这是因为我做错了(显然)或者我需要做更多的事情来强制约束来实现UIView高度大于零。
如何设置redBox高度约束,使其始终是BoxView高度的一半?
import UIKit
class BoxView: UIView {
public var redBox: UIImageView
public override init(frame: CGRect) {
redBox = UIImageView(frame: .zero)
redBox.backgroundColor = .red
super.init(frame: frame)
self.backgroundColor = .yellow
addSubview(redBox)
redBox.translatesAutoresizingMaskIntoConstraints = false
let margins = layoutMarginsGuide
redBox.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
redBox.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
redBox.widthAnchor.constraint(equalToConstant: 100).isActive = true
//redBox.heightAnchor.constraint(equalToConstant: 100).isActive = true
redBox.heightAnchor.constraint(equalTo: self.heightAnchor, constant: 0.5)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view = BoxView()
}
}
更换
redBox.heightAnchor.constraint(equalTo: self.heightAnchor, constant: 0.5)
同
redBox.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 0.5).isActive = true
NSLayoutConstraint.activate([
redBox.centerXAnchor.constraint(equalTo: self.centerXAnchor),
redBox.centerYAnchor.constraint(equalTo: self.centerYAnchor),
redBox.widthAnchor.constraint(equalToConstant: 100),
redBox.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 0.5)
])
在你当前的代码中,首先你会错过.isActive = true
,它具有与行不存在时相同的效果,如果指定这将使框高度等于视图的高度+常量(= 0.5)
box height = view height * multiplier + constant
并且由于默认乘数= 1并且您设置常数= 0.5,这将是
box height = view height * 1.0 + 0.5
但你需要
box height = view height * 0.5 + 0 //在约束中省略常量,它将为零
class BoxView: UIView {
public var redBox: UIImageView
public override init(frame: CGRect) {
super.init(frame: frame)
redBox = UIImageView(frame: .zero)
redBox.backgroundColor = .red
self.backgroundColor = .yellow
addSubview(redBox)
redBox.translatesAutoresizingMaskIntoConstraints = false
let margins = layoutMarginsGuide
NSLayoutConstraint.activate([
redBox.centerXAnchor.constraint(equalTo: self.centerXAnchor),
redBox.centerYAnchor.constraint(equalTo: self.centerYAnchor),
redBox.widthAnchor.constraint(equalToConstant: 100),
redBox.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 0.5)
])
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}