如何在集合单元格中重绘动态大小的 UIView

How to redraw a dynamically sized UIView within a collection cell

我有一个 UICollectionView,每个 UICollectionViewCell 里面都有一个 UIView,我根据内容动态调整大小...

我在单元格上设置模型的数据源:

extension CategoryViewController: UICollectionViewDataSource {
    // Show quiz thumbnail and name
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: QuizViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! QuizViewCell

        cell.quiz = self.quizzes[indexPath.row]

        return cell
    }
}

cell.quiz 是计算的 属性。设置好后,我根据难度计算出一个"progress bar"的宽度。为简单起见,我在这里将其设置为 100。

class QuizViewCell: UICollectionViewCell {
    @IBOutlet weak var difficultyBar: UIView!

    var quiz: Quiz? {
        didSet {
            configure(quiz)
        }
    }

    private func configure(_ quiz: Quiz?) {
        if let quiz = quiz {
            difficultyBar.frame = CGRect(x: 0, y: 0, width: 100, height: 6)

            // Attempt to redraw bar, but doesn't work
            setNeedsLayout()
            layoutIfNeeded()
        }
    }
}

我知道,如果不是为了收集,我可以在控制器上调用 view.layoutIfNeeded() 以强制它重新绘制栏,因为它的宽度已设置。但是我不知道在哪里或如何强制它重绘集合视图中单元格内的视图。

根据您的评论,更改框架将不起作用,因为您正在使用约束

因此为 difficultyBar 宽度创建约束

@IBOutlet weak var difficultyBarWidthConstraint: NSLayoutConstraint! //set this to the width of difficultyBar

然后在 QuizViewCell 中更新宽度约束常数

private func configure(_ quiz: Quiz?) {
    if let quiz = quiz {
        if difficultyBarWidthConstraint != nil {
            difficultyBarWidthConstraint.constant  = 100// width you want to set
        }

    }
}

让我知道这是否可行:-)