UICollectionView 单元格重叠 swift

UICollectionView cells overlapping swift

我正在创建一个 UICollectionView,但是当一个新的单元格被添加到视图时,它与前一个单元格部分重叠。下面是我的代码:

 override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {


    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CustomCell", forIndexPath: indexPath) as! CustomCell

    cell.frame.size.width = self.view.frame.width / 3
    cell.frame.size.height = self.view.frame.height / 4
    cell.backgroundView = imageView
    return cell

}

如何确保单元格不重叠?

你不应该在 cellForItemAtIndexPath 方法中自己分配帧值。

更合适的方法是在 UICollectionViewLayout 中执行此操作,然后将其设置为集合视图的布局 属性。实际上,当您初始化 UICollectionView 实例时,您需要一个 UICollectionViewLayout 实例。

或者简单的说,使用系统提供的UICollectionViewFlowLayout方便的实现流式布局,通过delegate告诉它每个单元格的大小,单元格之间的间距,以及其他一些信息。布局实例都会为你安排好。

例如

class MYViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

    //In viewDidLoad()
    var collectionViewFlowLayout = UICollectionViewFlowLayout()
    var myCollectionView = UICollectionView(frame: self.view.bounds, layout: collectionViewFlowLayout)
    // A flow layout works with the collection view’s delegate object to determine the size of items, headers, and footers in each section and grid. 
    // That delegate object must conform to the UICollectionViewDelegateFlowLayout protocol.
    myCollectionView.delegate = self
    myCollectionView.dataSource = self

    // MARK: UICollectionViewDelegateFlowLayout
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        return CGSizeMake(10, 10);
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
         return 10;
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
        return 10;
    }
}

有关详细信息,请阅读 doc

对我来说,这是在视图控制器的尺寸检查器中指定的错误单元格宽度和高度。只需正确设置它可能与您的 nib 文件相同,它可能会起作用。

为了清楚起见,请查看屏幕截图。

您所需要的只是从 UICollectionViewDelegateFlowLayout 扩展 ViewController 并实施 sizeForItemAt :

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    
    if (collectionView == myCollectionView_1) {
        
        return CGSize(width: self.view.frame.width / 3, height: self.view.frame.height / 4)
        
    } else {
        
        return collectionView.frame.size
    }
    
}

对我来说,只需在集合视图选项中将 Estimated Size 更改为 None 即可解决问题。

参考以下截图: