我正在尝试将 UICollectionView
添加到 ViewController
,我需要有3个单元格'per row',单元格之间没有空格(它应该看起来像一个网格) . 单元格宽度应该是屏幕尺寸的三分之一,所以我认为 layout.item
宽度应该相同 . 但后来我明白了:
如果我减小那个尺寸(例如7或8像素),那就更好了,但是行中的第三个单元格不是完全可见的,我仍然有那个空白区域(顶部和底部,左侧和右侧) .
class ViewController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
var collectionView: UICollectionView?
var screenSize: CGRect!
var screenWidth: CGFloat!
var screenHeight: CGFloat!
override func viewDidLoad() {
super.viewDidLoad()
screenSize = UIScreen.mainScreen().bounds
screenWidth = screenSize.width
screenHeight = screenSize.height
// Do any additional setup after loading the view, typically from a nib
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 20, left: 0, bottom: 10, right: 0)
layout.itemSize = CGSize(width: screenWidth / 3, height: screenWidth / 3)
collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
collectionView!.dataSource = self
collectionView!.delegate = self
collectionView!.registerClass(CollectionViewCell.self, forCellWithReuseIdentifier: "CollectionViewCell")
collectionView!.backgroundColor = UIColor.greenColor()
self.view.addSubview(collectionView!)
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 20
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionViewCell", forIndexPath: indexPath) as CollectionViewCell
cell.backgroundColor = UIColor.whiteColor()
cell.layer.borderColor = UIColor.blackColor().CGColor
cell.layer.borderWidth = 0.5
cell.frame.size.width = screenWidth / 3
cell.frame.size.height = screenWidth / 3
cell.textLabel?.text = "\(indexPath.section):\(indexPath.row)"
return cell
}
}
8 回答
添加这两行
所以你有了:
这将删除所有空格并为您提供网格布局:
如果您希望第一列的宽度等于屏幕宽度,请添加以下函数:
网格布局现在看起来像(我还为第一个单元格添加了蓝色背景):
For Swift 3 and XCode 8 ,这很有效 . 按照以下步骤实现此目的: -
将此代码放入viewDidLoad()函数中 .
在某些情况下,在
viewDidLoad
或ViewWillAppear
中设置UICollectionViewFlowLayout
可能不会对collectionView产生影响 .在
viewDidAppear
中设置UICollectionViewFlowLayout
可能会导致在运行时看到单元格大小的更改 .另一个解决方案,在Swift 3中:
如果您正在寻找Swift 3,请按照以下步骤来实现:
这在使用Swift 3的Xcode 8.0上得到验证 .
Swift 4
For Swift 3 and XCode 8, 这个有效 . 按照以下步骤实现此目的: -
对于Swift 3和Xcode 9尝试使用它