当请求完成并且我有来自服务器的图像时,我需要更新约束(我的 CollectionView 的高度),因此 View 的高度也会改变。
结果屏幕
我需要什么屏幕
我的代码:
DispatchQueue.main.async {
self.cvActivity.alpha = 0
self.collectionView.reloadData()
self.collectionView.heightAnchor.constraint(equalToConstant: self.cellWidth * 2).isActive = true
self.collectionView.setNeedsUpdateConstraints()
self.collectionView.setNeedsLayout()
self.view.layoutIfNeeded()
}
最佳答案
好吧,@J 的基本想法。 Doe 是正确的,这里有一些代码解释(为简单起见,我使用了 UIView
,而不是 UICollectionView
):
import UIKit
class ViewController: UIViewController {
@IBOutlet var heightConstraint: NSLayoutConstraint! // link the height constraint to your collectionView
private var height: CGFloat = 100 // you should keep constraint height for different view states somewhere
override func updateViewConstraints() {
heightConstraint.constant = height // set the correct height
super.updateViewConstraints()
}
// update height by button press with animation
@IBAction func increaseHight(_ sender: UIButton) {
height *= 2
UIView.animate(withDuration: 0.3) {
self.view.setNeedsUpdateConstraints()
self.view.layoutIfNeeded() // if you call `layoutIfNeeded` on your collectionView, animation doesn't work
}
}
}
结果:
关于ios - 更新约束 swift layoutIfNeeded 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48150039/