如何不与viewWillLayoutSubviews陷入无限循环?

时间:2017-06-07 13:31:56

标签: ios swift uitableview

我有一个带有单元格和标题的tableView。 header由堆栈视图中的两个视图组成。每次tableView宽度改变时,我都会设置标题的特定高度。

问题:如何不陷入无限循环?这是代码:

override func viewWillLayoutSubviews() {
    super.viewWillLayoutSubviews()

    guard let flowLayout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout else {
        return
    }

    UIView.animate(withDuration: 0.5, animations: { [weak self] (_) in
        self?.tableView.beginUpdates()
        if (self?.filtersView.isHidden)! {
            self?.filtersViewHeight.constant = .leastNormalMagnitude
            self?.stackView.bounds.size.height = 45
        } else {
            self?.filtersViewHeight.constant = 100
            self?.stackView.bounds.size.height = 45 + (self?.filtersViewHeight.constant)!
        }
        }, completion: { [weak self] (_) in
            flowLayout.invalidateLayout()

            self?.tableView.endUpdates() <---- this is wrong, as it forces the infinite loop.
    })
}

1 个答案:

答案 0 :(得分:4)

您应该从viewWIllLayoutSubviews中取出此功能并将其置于其自己的功能中。为动画调用该函数,并调用动画块中的setNeedsLayout。可以出于多种原因调用viewWillLayoutSubviews

tableView beginUpdatesendUpdates通知视图tableView或其中的部分内容需要重绘,因此它将调用viewWillLayoutSubviews