Ios UICollectionView单元格重叠
我正在创建一个UICollectionView,但是当一个新单元添加到视图中时,它部分地与上一个单元重叠。下面是我的代码:Ios UICollectionView单元格重叠,ios,swift,uikit,uicollectionview,Ios,Swift,Uikit,Uicollectionview,我正在创建一个UICollectionView,但是当一个新单元添加到视图中时,它部分地与上一个单元重叠。下面是我的代码: override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableC
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
中执行此操作,然后将其设置为collectionview的布局属性。实际上,在初始化UICollectionView
实例时,需要一个UICollectionViewLayout
实例
或者简单地说,使用系统提供的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;
}
}
有关更多信息,请阅读。对我来说,这是视图控制器的大小检查器中指定的错误单元格宽度和高度。只要将其正确地设置为可能与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
}
}
谢谢,你能给我举个例子说明怎么做吗?@Horatio请看我的例子。答案很好!谢谢@Horatio很乐意提供帮助:)那么您从这两个实例方法
minimunLineSpacingForSectionAtIndex
和minimumInItemSpacingForSectionAtIndex
中得到了重叠行为?