ios - 更新约束 swift layoutIfNeeded 不起作用

标签 ios swift layout constraints

当请求完成并且我有来自服务器的图像时,我需要更新约束(我的 CollectionView 的高度),因此 View 的高度也会改变。

结果屏幕

enter image description here

我需要什么屏幕

enter image description here

我的代码:

            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
        }
    }

}

结果:

enter image description here

关于ios - 更新约束 swift layoutIfNeeded 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48150039/

相关文章:

iOS 如何在文件的 xattr 中存储 NSDictionary 或 JSON?

ios - 从 UIViewController 添加 View

ios - 使用 Enterprise Distribution 获取 __hidden at Crashlytics 错误报告

layout - graphviz:圆形布局,同时保留节点顺序

java - Android:如何获取翻转器内布局的ID?

ios - 如何将 ViewController 中的数组数据传递给 UICollectionView 自定义单元格?

ios - 这是在闭包中使用 weak self 的正确位置吗?

swift - Xcode 6.3 中的 Git : Master branch showing new files from other branches in red and won't compile

swift - 使用 `SKNode` 作为 "world container"触发 NSException

javascript - HTML 编码顺序与布局问题