UICollectionView单元重叠swift

Hor*_*tio 2 uikit ios uicollectionview 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

}
Run Code Online (Sandbox Code Playgroud)

如何确保细胞不重叠?

liu*_*obe 6

您不应该在cellForItemAtIndexPath方法中自己分配帧值.

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

或者简单地说,使用UICollectionViewFlowLayout哪个系统提供方便地实现流布局,告诉它每个单元格的大小,它们之间的空格,以及它的委托的一些其他信息.布局实例将为您安排所有内容.

例如.

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请阅读文档.