2
其他單元格這是我在SWIFT 3UICollectionView斯威夫特卡倫特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個單元格。
uncorrect結果
[XXX]
[XXX]
[XXX]
[XXX]
[XXX]
[XXX]
正確的結果
[XXX]
[XXX]
[XXX]
[XXX]
[XXX]
[XX]
因爲你是返回'numberOfItemsInSection'爲3。 – Santosh