如果numberOfItemsInSection为1,则不调用cellForItemAt

以下是我的代码,如果numberOfItemsInSection大于1,但工作正常,但如果numberOfItemsInSection等于1,则应显示单个单元格,但不会发生,因为numberOfItemsInSection等于1,将显示注释,并且不调用cellForItemAt

    tabsCollectionView.delegate = self
    tabsCollectionView.dataSource = self




func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return menuResult?.foodMenuItems?.count ?? 0
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = tabsCollectionView.dequeueReusableCell(withReuseIdentifier: "foodTabsCollectionViewCellID", for: indexPath) as! FoodTabsCollectionViewCell
    cell.foodMenuItem = menuResult?.foodMenuItems?[indexPath.row]
    cell.setUI()
    return cell
}


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

}

以下代码与side viewDidLoad()中的大小相关

 if let flowLayout = tabsCollectionView.collectionViewLayout as? UICollectionViewFlowLayout {
        flowLayout.estimatedItemSize = CGSize(width: 200, height: 70)
        flowLayout.itemSize = UICollectionViewFlowLayout.automaticSize
        tabsCollectionView.collectionViewLayout = flowLayout
    }

sizeForItemAt方法

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

    return CGSize(width: width, height: height)
}

以下是FoodTabsCollectionViewCell内部的代码

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