如何将 UIView 限制为 UICollectionViewCell

How do I constrain UIView to UICollectionViewCell

与其他人似乎在问的相反。我有一个带有单元格的 collectionView,我将加载的 .xib 作为子视图添加到其中。很容易。

但是,collectionView 单元格的大小会根据不同的标准在 运行 时发生变化,因此我需要将子视图适当地限制为 collectionViewCell 的 contentView 的大小。在尝试这样做时,我在添加子视图时有以下代码:

/**
Used to present a view in the collectionView. WidetView is a subclass of UIView
*/
class WidgetCell: UICollectionViewCell, Reusable {
    var widgetView: WidgetView! {
        didSet {
            for view in contentView.subviews {
                view.removeFromSuperview()
            }

            contentView.addSubview(widgetView)
            let views = ["view": widgetView as Any]
            var constraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[view]-0-|", options: .directionLeadingToTrailing, metrics: nil, views: views)
            constraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[view]-0-|", options: .directionLeadingToTrailing, metrics: nil, views: views))

            contentView.addConstraints(constraints)
        }
    }
}

不幸的是,呈现的不是一组适当约束的视图。添加的 UIView 与 .xib 中定义的大小相同。

我该如何解决这个问题?如果您想要示例项目 (Swift 3),请看这里:https://github.com/AaronBratcher/FitToCell

这是一个简单的例子,使用现有代码调用 contentView.activateConstraints(constraints),然后在显示单元格的位置调用 cell.layoutIfNeeded()。这会强制单元格重新计算其子视图的边界。

由于单元格的预期大小对于布局而言是已知的,因此将该大小传递给 WidgetCell 实例,然后设置视图的框架大小。

final class WidgetCell: UICollectionViewCell {
    var cellSize: CGSize?
    var widgetView: WidgetView! {
        didSet {
            for view in contentView.subviews {
                view.removeFromSuperview()
            }

            let frame: CGRect
            if let cellSize = cellSize {
                frame = CGRect(origin: CGPoint(x: 0, y: 0), size: cellSize)
            } else {
                frame = contentView.frame
            }

            widgetView.frame = frame
            widgetView.setNeedsLayout()
            contentView.addSubview(widgetView)
        }
    }
}