我正在创建一个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
}
如何确保细胞不重叠?
答案 0 :(得分: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;
}
}
有关详细信息,请阅读doc。
答案 1 :(得分:0)
答案 2 :(得分:0)
您所需要的只是从 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
}
}