【发布时间】:2016-09-23 19:36:03
【问题描述】:
这是我在 swift 3 中的代码
class BSViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
let reuseIdentifier = "cell" // also enter this string as the cell identifier in the storyboard
var items = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14","15","16"]
// MARK: - UICollectionViewDataSource protocol
// tell the collection view how many cells to make
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 3
}
// make a cell for each cell index path
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// get a reference to our storyboard cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! MyCollectionViewCell
// Use the outlet in our custom class to get a reference to the UILabel in the cell
cell.myLabel.text = self.items[indexPath.item]
cell.backgroundColor = UIColor.cyan // make cell more visible in our example project
return cell
}
// MARK: - UICollectionViewDelegate protocol
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// handle tap events
print("You selected cell #\(indexPath.item)!")
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
if self.items.count % 3 > 0 {
print(self.items.count % 3)
return (self.items.count/3)+1
}
else {
return self.items.count/3
}
}
private func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
{
var collectionViewSize = collectionView.frame.size
collectionViewSize.width = collectionViewSize.width/3.0 //Display Three elements in a row.
collectionViewSize.height = collectionViewSize.height/4.0
return collectionViewSize
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "Footer", for: indexPath)
// configure footer view
return view
}
}
结果,它显示了 6 行,每行有 3 个单元格,并且必须是 6 行,每行包含 3 个单元格,期望最后一行必须有 2 个剩余单元格。
结果不正确
[ X X X ]
[ X X X ]
[ X X X ]
[ X X X ]
[ X X X ]
[ X X X ]
正确的结果
[ X X X ]
[ X X X ]
[ X X X ]
[ X X X ]
[ X X X ]
[X X]
【问题讨论】:
-
因为您将
numberOfItemsInSection作为 3 返回。
标签: ios iphone swift xcode uicollectionview