我在collectionview中的自动调整大小单元格调整了两次

时间:2019-04-04 17:55:30

标签: ios swift uicollectionview cell autoresize

我想根据内容自动调整collectionview的单元格大小。当我单击一个单元格时,好像该单元格的大小调整了两次。

我做了什么: handling circular dependencies

我的代码:

MainViewController.swift

override func viewDidLoad() {
        super.viewDidLoad()

if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
            layout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
        }
}

我也没有运气尝试过这个

override func viewDidLoad() {
        super.viewDidLoad()

if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout,
            let collectionView = collectionView {
            let width = (collectionView.frame.width - 70) / 1.9
            let height = (collectionView.frame.height - 100) / 10
            layout.estimatedItemSize = CGSize(width: width, height: height)
        }
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

        let width = view.frame.size.width - 40
        let height = (view.frame.size.height - 100) / 6
        let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: width, height: height)


        if indexPath.section == 1 {
            let width = (view.frame.size.width - 70) / 1.9
            let height = (view.frame.size.height - 100) / 10
            let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
            layout.itemSize = CGSize(width: width, height: height)
            return layout.itemSize
        }

        if indexPath.section == 2 {
            let width = (view.frame.size.width - 70) / 1.9
            let height = (view.frame.size.height - 100) / 10
            let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
            layout.itemSize = CGSize(width: width, height: height)
            return layout.itemSize
        }

        return layout.itemSize
    }

MyBusinessCell.swift:

override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
        setNeedsLayout()
        layoutIfNeeded()
        let size = contentView.systemLayoutSizeFitting(layoutAttributes.size)
        var frame = layoutAttributes.frame
        frame.size.height = ceil(size.height)
        layoutAttributes.frame = frame
        return layoutAttributes
    }

PS:我认为调整大小是可行的,但是为什么要这样做两次呢?

0 个答案:

没有答案