使用 flowLayout 自动调整 collectionView

self sizing collectionView with flowLayout

当我在没有

的情况下使用 collectionView 时
let flowLayout = collectionView.collectionViewLayout as!  UICollectionViewFlowLayout 
flowLayout.estimatedItemSize = CGSize (width: self.collectionView.frame.width, height: 100) 

然后显示所有单元格,但是当我使用 flowLayout 时,单元格不显示我已经在这里坐了一个星期了,不明白为什么会这样。

这是我的代码

override func viewDidLoad() {
    super.viewDidLoad()

    collectionView.delegate = self
    collectionView.dataSource = self

    let flowLayout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout

    flowLayout.estimatedItemSize = CGSize(width: self.collectionView.frame.width, height: 100)



    requestD(url: url)

}

// MARK: UICollectionViewDataSource

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}


func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return modals.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    if modals.count == 0 {
        return UICollectionViewCell()
    }
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCellAudio


    cell.name?.text = modals[indexPath.row].name


    let u = URL(string: "http://www.---.com" + (modals[indexPath.row].ImageViewURL))
    cell.ImageView.sd_setImage(with: u, placeholderImage: UIImage(named: "white"),
                               options: [.continueInBackground,.scaleDownLargeImages]) { (image, error, cacheType, url) in

                                self.modals[indexPath.row].ImageView = cell.ImageView.image!

    }  

    return cell  
}

func requestD(url:String){


    var urlRequest = URLRequest(url: URL(string: url)!)
    urlRequest.timeoutInterval = 300



    let task = URLSession.shared.dataTask(with: urlRequest) { (data,response,error) in

        if error != nil{
            print(error ?? 0)
            return
        }
        do{
            let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : Any]

            if let main = json["LIBRARY"] as? [String:[String : Any]]{

                for (_, data) in main {
                    let info = ModalAudio()
                    info.id = data["ID"] as? String
                    info.name = data["NAME"] as? String
                    info.AboutBook = data["DETAIL_TEXT"] as? String
                    info.ImageViewURL = data["PICTURE"] as! String

                    self.modals.append(info)


                }
            }

        } catch let error {
            print(error)
        }

        DispatchQueue.main.sync {

            self.isMoreDataLoading = false
            self.iNumPage += 1

        }
    }

    self.collectionView?.reloadData()
    task.resume()

}

viewDidLoad 中,您的集合视图的框架尚未定义,因此请将此代码放入您的 viewDidLayoutSubView 方法中,在检查您的项目后,您的问题与使用 flowLayout.estimatedItemSize 正如您在 属性 声明注释

中所读
@available(iOS 8.0, *)
open var estimatedItemSize: CGSize // defaults to CGSizeZero - setting a non-zero size enables cells that self-size via -preferredLayoutAttributesFittingAttributes:

所以使用这段代码,有效

    override func viewDidLayoutSubviews() {
            super.viewDidLayoutSubviews()
            let flowLayout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout

            //flowLayout.estimatedItemSize = CGSize(width: self.collectionView.frame.width, height: 100) don't show your cells
            flowLayout.itemSize = CGSize(width: self.collectionView.frame.width, height: 100)//show your cells
            flowLayout.invalidateLayout() 
        }

希望对您有所帮助