更新约束 swift layoutIfNeeded 不起作用

Вла*_*тов 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)

pac*_*ion 5

好吧,@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)

结果:

在此处输入图片说明