Swift_UI:(九)、UICollectionView

许正平
2023-12-01

import UIKit


class ViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource {


    override func viewDidLoad() {

        super.viewDidLoad()

        

        let layout = UICollectionViewFlowLayout()

        layout.scrollDirection = .vertical

        layout.minimumLineSpacing = 50

        layout.minimumInteritemSpacing = 30

        layout.itemSize = CGSize(width:100,height:100)

        layout.headerReferenceSize = CGSize(width:self.view.bounds.size.width,height:100)

        layout.footerReferenceSize = CGSize(width:self.view.bounds.size.width,height:100)

        layout.sectionInset = UIEdgeInsetsMake(10, 20, 10, 20)

        let collectionView = UICollectionView(frame:self.view.bounds,collectionViewLayout:layout)

        collectionView.register(NSClassFromString("UICollectionViewCell"), forCellWithReuseIdentifier: "collectioncell")

        self.view.addSubview(collectionView)

        

        

        collectionView.delegate = self

        collectionView.dataSource = self

        

        // Do any additional setup after loading the view, typically from a nib.

    }


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

        return 1

    }

    

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

        return 27

    }

    

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

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

        cell.backgroundColor = UIColor.red

        return cell

    }

    

    

    

    

    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }



}


 类似资料: