Display UICollectionView with 2 columns of equal size square cells

耗尽温柔 提交于 2021-01-28 06:48:08

问题


I'm trying to accomplish the following:

I've followed the answer in this question, but I get the image below:

This is the code for the collection view controller:

class MainMenuViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {



    @IBOutlet var collectionView: UICollectionView!
    @IBOutlet weak var dateTimeLabel: MarqueeLabel!
    @IBOutlet weak var iconButton: UIButton!
    @IBOutlet var imageView: UIImageView!

    var iconButtonTimer: Timer!
    var upDateTimer: Timer!

    var statusString: String!
    var alertTitle: String!
    var networkStatusString: String!




    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView.dataSource = self
        collectionView.delegate = self

        collectionView.register(UINib.init(nibName: "MainMenuCell", bundle: nil), forCellWithReuseIdentifier: "MainMenuCell")

        collectionView.collectionViewLayout = MainMenuLayout()
    }


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

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

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        print(#function)
        let padding: CGFloat =  50
        let collectionViewSize = collectionView.frame.size.width - padding

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




    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MainMenuCell", for: indexPath)

         cell.backgroundColor = UIColor.red

        return cell
    }
}

And this is the storyboard...


回答1:


Conform to UICollectionViewDelegateFlowLayout and implement

func collectionView(_ collectionView: UICollectionView,
                    layout collectionViewLayout: UICollectionViewLayout,
                    insetForSectionAt section: Int) -> UIEdgeInsets {

    return UIEdgeInsetsMake(10, 10, 10, 10)
}

Also comment this line

collectionView.collectionViewLayout = MainMenuLayout()

as no need for a custom layout to accomplish what you want



来源:https://stackoverflow.com/questions/51818189/display-uicollectionview-with-2-columns-of-equal-size-square-cells

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!