Using CollectionView in UIView with xib file

后端 未结 2 1675
广开言路
广开言路 2020-12-08 11:41

i\'m doing with this, i want to use CollectionView, but i haven\'t seen prototype cell, and don\'t know how to use CollectionView in this case, can someone help me ?

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-08 12:26

    ok first you must have the IBOutlet of your collection view and implements the methods like this

    class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
    
    
    
        @IBOutlet var collectionView: UICollectionView!
    
        override func viewDidLoad() {
    
            super.viewDidLoad()
            count = 9;
            let nib = UINib(nibName: "yourItemView", bundle: nil)
            collectionView.registerNib(nib, forCellWithReuseIdentifier: "yourItemView")
            self.collectionView.delegate = self
            self.collectionView.dataSource = self
    
    
        }
    

    ok in the function you add a xib file, next you must create that extend from UICollectionViewCell, and when you finish this you must override the next methods

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return count 
            // the numbers of items
        }
    
        func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {//size of your item for screen sizes
            let wsize = UIScreen.mainScreen().bounds.size.width
            switch(wsize){
            case 414:
                return CGSize(width: 190, height: 102)
            case 375:
                return CGSize(width: 190, height: 102)
            case 320:
                return CGSize(width: 174, height: 102)
            default:
                return CGSize(width: 174, height: 102)
            }
        }
    
    
    
        func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    
            let cell = collectionView.dequeueReusableCellWithReuseIdentifier("yourItemView", forIndexPath: indexPath) as! yourItemView
    
    
    
            return cell
        }
    

    and this is all, good luck

提交回复
热议问题