我想将UIView的大小设置为height = (width - 100) * 0.5
,因此代码如下:
view.snp.makeConstraints {
$0.top.left.right.equalTo(0)
$0.height.equalTo(view.snp.width).offset(-100).multipliedBy(0.5)
}
但高度结果等于width * 0.5 - 100
,
如何更改offset()
和multipliedBy()
的优先级?
我想如果您想在说明中使用height = (width - 100) * 0.5
,则您的代码应更改为类似以下内容:-
view.snp.makeConstraints {
$0.top.left.right.equalTo(8)
let calculatedHeight:CGFloat = (view.snp.width - 100) * 0.5
$0.height.equalTo(calculatedHeight).priority(.required)
}
并且您可以使用枚举SnapKit的ConstraintPriority更改优先级,如上面的示例代码上的官方documentation检查中所述。
您已经发现,自动布局首先应用multiplier,然后应用constant。
摘自苹果公司的文档:
要实现您的目标,您需要使用其他视图,或者最好使用UILayoutGuide
。
告诉自动布局,您希望otherView / layoutGuide为viewWidth - 100
,然后您希望视图为那个值 * 0.5
。
这里是一个例子:
class SnapTestViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// create a view
let testView = UIView()
testView.backgroundColor = .orange
// create a Layout Guide
let vGuide = UILayoutGuide()
// add the layout guide to the testView
testView.addLayoutGuide(vGuide)
// constrain the layout guide
vGuide.snp.makeConstraints {
// to bottom-left corner
$0.leading.bottom.equalToSuperview()
// height doesn't really matter (it's not visible)
$0.height.equalTo(1)
// width = superView (testView) width - 100
$0.width.equalToSuperview().offset(-100)
}
// add testView to self.view
view.addSubview(testView)
// constrain testView
testView.snp.makeConstraints {
// 40-pts leading and trailing
$0.leading.trailing.equalToSuperview().inset(40)
// 100-pts from the top
$0.top.equalToSuperview().offset(100)
// height = layoutGuide height * 0.5
$0.height.equalTo(vGuide.snp.width).multipliedBy(0.5)
}
}
}