Swift - Basic usage of the default UICollectionViewController for the system

Keywords: Mobile Swift

When you create without xib, you need to rewrite

override init(collectionViewLayout layout: UICollectionViewLayout){}

The UICollectionViewLayout value needs to be passed when invoking, otherwise an error will be reported.

 let layout = UICollectionViewFlowLayout.init()
                
 let vc1 = DataCollectionViewController.init(collectionViewLayout: layout)

Next is the registration and invocation of the cell.

self.collectionView!.register(DataCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
 override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return self.leagueNameArr.count
    }
 override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! DataCollectionViewCell
        cell.titleLabel.text = self.leagueNameArr[indexPath.item]
    
        return cell
    }

If you need to set the size of item and the distance from top left to bottom right, add UICollection View Delegate Flow Layout protocol and follow the method

  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize.init(width: 60, height: 30)
    }
    
  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets.init(top: 5, left: 10, bottom: 5, right: 10)
    }
    

At this point, "run" will find that the background color of view is black. We need to set the background color in the override init(collectionViewLayout layout: UICollectionViewLayout) {} method.

        self.collectionView?.backgroundColor = UIColor.init(red: 237/255, green: 237/255, blue: 237/255, alpha: 1)

ok, that's about all.

Posted by darkwolf on Sat, 02 Feb 2019 11:00:16 -0800