Получить динамическую высоту для UICollectionViewCell с пользовательским макетом

Я столкнулся с этим до того, как пришел к тому же выводу о кросс-запросах базы данных, как и вы. То, что я закончил, было использование схем для разделения табличного пространства таким образом, чтобы я мог хранить таблицы сгруппированными, но все еще запрашивать их все.

0
задан rmvz3 18 March 2019 в 23:28
поделиться

1 ответ

Вы можете рассчитать высоту клетки с помощью функции systemLayoutSizeFitting.

https://developer.apple.com/documentation/uikit/uiview/1622623-systemlayoutsizefitting

Например: (UICollectionViewCell является подклассом UICollectionReusableView, поэтому вы можно использовать это и для ячеек и верхнего / нижнего колонтитула)

public extension UICollectionReusableView {
    static func autoResizingView<T: UICollectionReusableView>(type: T.Type) -> T {
        let nibViews = Bundle.main.loadNibNamed(T.identifier, owner: nil, options: nil)
        return nibViews?.first as? T ?? T()
    }

    static func autoLayoutSize<T: UICollectionReusableView>(type: T.Type, targetWidth: CGFloat, configure: ((T) -> Void)?) -> CGSize {
        let resizingView = UICollectionReusableView.autoResizingView(type: type)
        resizingView.prepareForReuse()
        configure?(resizingView)
        resizingView.setNeedsLayout()
        resizingView.layoutIfNeeded()

        let targetSize = CGSize(width: targetWidth, height: 0)
        let calculateView: UIView
        if let contentView = (resizingView as? UICollectionViewCell)?.contentView {
            calculateView = contentView
        } else {
            calculateView = resizingView
        }
        // Calculate the size (height) using Auto Layout
        let autoLayoutSize = calculateView.systemLayoutSizeFitting(
            targetSize,
            withHorizontalFittingPriority: .required,
            verticalFittingPriority: .defaultLow)
        return autoLayoutSize
    }
}
0
ответ дан Quoc Nguyen 18 March 2019 в 23:28
поделиться
Другие вопросы по тегам:

Похожие вопросы: