Вла*_*тов 4 layout constraints ios swift
当请求完成并且我有来自服务器的图像时,我需要更新约束(我的 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()
}
Run Code Online (Sandbox Code Playgroud)
好吧,@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
}
}
}
Run Code Online (Sandbox Code Playgroud)
结果:
| 归档时间: |
|
| 查看次数: |
8861 次 |
| 最近记录: |