如何使两行水平收集视图?

时间:2018-09-30 01:26:58

标签: ios swift uicollectionview

我想像下面这样水平制作两行集合视图

enter image description here

我是iOS开发的新手,有些教程仅给出示例如何垂直设置集合视图的特定列数,但我需要限制集合视图的行数

我试图将节的数量设为2,但仍然是,行的数量仍为1

import UIKit

class ViewController: UIViewController, UICollectionViewDataSource{

    @IBOutlet var collectionView: UICollectionView!


    let imageArray = [UIImage(named: "image1"),UIImage(named: "image2"),UIImage(named: "image3"),UIImage(named: "image4"),UIImage(named: "image5"),UIImage(named: "image6"),UIImage(named: "image8"),UIImage(named: "image9")]

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 2
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageArray.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "imageCell", for: indexPath) as! ImageCell
        cell.avatarView.image = imageArray[indexPath.item]
        return cell
    }


}

enter image description here

2 个答案:

答案 0 :(得分:0)

Please update the section inset

func numberOfSections(在collectionView中:UICollectionView)-> Int {         返回     }     func collectionView(_ collectionView:UICollectionView,numberOfItemsInSection部分:Int)-> Int {         返回imageArray.count     }

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "imageCell", for: indexPath) as! ImageCell
    cell.avatarView.image = imageArray[indexPath.item]
    return cell
}

public func collectionView(_ collectionView:UICollectionView,布局collectionViewLayout:UICollectionViewLayout,sizeForItemAt indexPath:IndexPath)-> CGSize {

    let padding: CGFloat =  60
    let collectionViewSize = collectionView.frame.size.height - padding

    return CGSize(width: 100, height: collectionViewSize/2)
}

答案 1 :(得分:0)

在代码下方添加

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

        return CGSize(width: collectionView.frame.height/2, height: collectionView.frame.height/2)

    }

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }