我以编程方式创建了一个好习惯,一个投递箱。
除了动画之外,一切都正常。
这是我致电self.setNeedsLayout()
在这里,当我不使用self.setNeedsLayout()
我的自定义视图我将其插入了堆栈视图
这是我的自定义视图:
class FittoBoxView: UIView {
let headerView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = .gray
return view
}()
var open = true
var heightContraint: NSLayoutConstraint!
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
}
extension FittoBoxView {
func registerView(with constraint: NSLayoutConstraint) {
heightContraint = constraint
translatesAutoresizingMaskIntoConstraints = false
backgroundColor = .red
// Adding header
let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
headerView.addGestureRecognizer(tap)
addSubview(headerView)
headerView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
headerView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
headerView.heightAnchor.constraint(equalToConstant: 45).isActive = true
heightContraint.constant = 400
}
@objc func handleTap(_ sender: UITapGestureRecognizer? = nil) {
if open {
heightContraint.constant = 45
} else {
heightContraint.constant = 400
}
self.setNeedsLayout() // <------ IR
UIView.animate(withDuration: 1) {
self.layoutIfNeeded()
}
open = !open
}
}
该框的切换位于handleTap()
函数中
在我的控制器中,我创建如下视图:
let boxView = FittoBoxView()
stackView.insertArrangedSubview(boxView, at: 1)
let height = boxView.heightAnchor.constraint(equalToConstant: 100)
height.isActive = true
boxView.registerView(with: height)
为什么当我使用setNeedLayout时,视图会跳转?标签没有动画
我该如何制作动画,或者只是框的主体在动画中发生?