我怎样才能轻松地制作一个水平滚动集合视图,填充单元格跨越行而不是列向下?我希望有5列和3行,但是当有超过15个项目时,我希望它滚动到下一页.这件事情我有很多麻烦.
解决方法
选项1 – 推荐
为集合视图使用自定义布局.这是执行此操作的正确方法,它使您可以控制单元格如何填充集合视图.
这是来自“raywenderlich”的UICollectionView Custom Layout Tutorial
选项2
这更像是一种做你想做的事情的hackish方式.在此方法中,您可以按顺序访问数据源以模拟所需的样式.我将在代码中解释它:
var myArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18] let rows = 3 let columnsInFirstPage = 5 // calculate number of columns needed to display all items var columns: Int { return myArray.count<=columnsInFirstPage ? myArray.count : myArray.count > rows*columnsInFirstPage ? (myArray.count-1)/rows + 1 : columnsInFirstPage } override func collectionView(collectionView: UICollectionView,numberOfItemsInSection section: Int) -> Int { return columns*rows } override func collectionView(collectionView: UICollectionView,cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell",forIndexPath: indexPath) //These three lines will convert the index to a new index that will simulate the collection view as if it was being filled horizontally let i = indexPath.item / rows let j = indexPath.item % rows let item = j*columns+i guard item < myArray.count else { //If item is not in myArray range then return an empty hidden cell in order to continue the layout cell.hidden = true return cell } cell.hidden = false //Rest of your cell setup,Now to access your data You need to use the new "item" instead of "indexPath.item" //like: cell.myLabel.text = "\(myArray[item])" return cell }
以下是此代码的实际操作:
*“添加”按钮只是为myArray添加了另一个数字并重新加载了集合视图,以演示myArray中不同数量项目的外观
编辑 – 将项目分组到页面中:
var myArray = [1,18] let rows = 3 let columnsInPage = 5 var itemsInPage: Int { return columnsInPage*rows } var columns: Int { return myArray.count%itemsInPage <= columnsInPage ? ((myArray.count/itemsInPage)*columnsInPage) + (myArray.count%itemsInPage) : ((myArray.count/itemsInPage)+1)*columnsInPage } override func collectionView(collectionView: UICollectionView,forIndexPath: indexPath) let t = indexPath.item / itemsInPage let i = indexPath.item / rows - t*columnsInPage let j = indexPath.item % rows let item = (j*columnsInPage+i) + t*itemsInPage guard item < myArray.count else { cell.hidden = true return cell } cell.hidden = false return cell }