自定义collectionView with flowLayout

时间:2017-07-29 19:16:30

标签: ios swift uicollectionview uicollectionviewcell

当我使用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()

}

1 个答案:

答案 0 :(得分:2)

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() 
        }

希望这有帮助