更新约束swift layoutIfNeeded不起作用

时间:2018-01-08 12:10:58

标签: 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()
            }

3 个答案:

答案 0 :(得分:3)

嗯,@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

答案 1 :(得分:1)

您需要从故事板

制作高度约束的对象
 @IBOutlet weak var YourHeightConstraintName: NSLayoutConstraint!


  YourConstraintName.constant = valueYouWantToGive

--------- -------- OR

  collectionViewOutlet.view.frame = CGRect(x: 
    collectionViewOutlet.frame.origin.x , y: 
    collectionViewOutlet.frame.origin.y, width: 
    collectionViewOutlet.frame.width, height: 
    yourheightValue)

答案 2 :(得分:1)

为collectionView定义高度,从该约束创建一个出口并增加该约束的常量并在动画块中调用layoutifneeded