我想通过动画更改uiview1(由NSLayoutConstraint视觉格式语言创建的宽度)
这是我的代码:
var constraintArray : [NSLayoutConstraint] = []
constraintArray += NSLayoutConstraint.constraints(withVisualFormat: "H:|-10-[uiview1]-10-|", options: [], metrics: nil, views: viewsDict)
constraintArray += NSLayoutConstraint.constraints(withVisualFormat: "H:|-10-[uiview2]-10-|", options: [], metrics: nil, views: viewsDict)
constraintArray += NSLayoutConstraint.constraints(withVisualFormat: "H:|-10-[uiview3]-10-|", options: [], metrics: nil, views: viewsDict)
constraintArray += NSLayoutConstraint.constraints(withVisualFormat: "V:|-100-[uiview1]-20-[uiview2]-30-[uiview3]-30-|", options: [], metrics: nil, views: viewsDict)
NSLayoutConstraint.activate(constraintArray)
func changeUIViewWidth{
//i don't know how to change width of uiview1 by animation
UIView.animate(withDuration: 3){
self.view.layoutIfNeeded()
}
}
我该怎么做?
答案 0 :(得分:1)
在您的情况下,这将具有挑战性,因为您没有uiview1
的任何显式宽度限制,可以在代码中进行更改。通过检查
constraintArray += NSLayoutConstraint.constraints(withVisualFormat: "H:|-10-[uiview1]-10-|", options: [], metrics: nil, views: viewsDict)
并调整从该行返回的每个约束(应该有两个约束)并更改其constant
。
let uiview1Constraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-10-[uiview1]-10-|", options: [], metrics: nil, views: viewsDict)
...
// Make uiview1 thinner
uiview1Constraints[0].constant = 20
uiview1Constraints[1].constant = 20
UIView.animate(withDuration: 3) {
self.view.layoutIfNeeded()
}
我建议您使用NSLayoutAnchor
创建约束。它更简单,更易于阅读,也更少出错。创建constant
后,您仍然可以直接对其进行操作。