UICollectionView programmatically swift

スポンサーリンク

UICollectionView

UICollecitonView is collection interface like list. Different from list, number and size and alignment, more flexible UI

In Android, no equal UI, recyclerview or grid view etc…

Example

  • UISampleCollectionView.swift (Main ViewController)
  • CollectionCellView.swift (Cell View)

UISampleCollectionView.swift

class UISampleCollectionView : UIViewController {
    
    var collectionView: UICollectionView!
    
    var titles : [String] = ["An", "Bob", "Cris", "Deep", "Earth"]
    
    private var layout : UICollectionViewFlowLayout {
        let layout : UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        let boundSize: CGSize = UIScreen.main.bounds.size
        layout.itemSize = CGSize(width: boundSize.width, height: 50)
        return layout
    }
    
    override func viewDidLoad() {
     
        self.collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: self.layout)
        self.collectionView.backgroundColor = UIColor.white
        self.collectionView.delegate = self
        self.collectionView.dataSource = self
        self.collectionView.register(CollectionCellView.self, forCellWithReuseIdentifier: "cell")
        self.collectionView.reloadData()
        self.view.addSubview(collectionView)
    }
}

extension UISampleCollectionView : UICollectionViewDelegate {
    
}

extension UISampleCollectionView : UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 5
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell : CollectionCellView = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionCellView
        cell.label?.text = titles[indexPath.row]
        
        return cell
    }
}

Steps

  • Create layout
  • Set delegate, later implement required methods in extension
  • Register cell same as UITableView
  • Reload data

CollectionCellView.swift

import Foundation
import UIKit

class CollectionCellView : UICollectionViewCell {
    
    var label: UILabel?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.create(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func create(frame: CGRect) {
        self.label = UILabel(frame: frame)
        self.contentView.addSubview(self.label!)
    }
}

Result

iOS
スポンサーリンク
Professional Programmer2

コメント