Wednesday, March 4, 2026
HomeiOS DevelopmentUICollectionView knowledge supply and delegates programmatically

UICollectionView knowledge supply and delegates programmatically



· 1 min learn


On this fast UIKit tutorial I am going to present you how one can create a easy UICollectionView with out Interface Builder, however solely utilizing Swift.

UICollectionViewCell programmatically

Should you’d like so as to add views to your cell, it’s best to use the init(body:) methodology, and arrange your view hierarchy there. As a substitute of awakeFromNib it’s best to type your views within the init methodology as nicely. You possibly can reset every little thing inside the same old prepareForReuse methodology. As you’ll be able to see by utilizing anchors typically it’s value to ditch IB fully. 🎉

class Cell: UICollectionViewCell {

    static var identifier: String = "Cell"

    weak var textLabel: UILabel!

    override init(body: CGRect) {
        tremendous.init(body: body)

        let textLabel = UILabel(body: .zero)
        textLabel.translatesAutoresizingMaskIntoConstraints = false
        contentView.addSubview(textLabel)
        NSLayoutConstraint.activate([
            contentView.centerXAnchor.constraint(equalTo: textLabel.centerXAnchor),
            contentView.centerYAnchor.constraint(equalTo: textLabel.centerYAnchor),
        ])
        self.textLabel = textLabel
        reset()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been applied")
    }

    override func prepareForReuse() {
        tremendous.prepareForReuse()
        
        reset()
    }

    func reset() {
        textLabel.textAlignment = .middle
    }
}

UICollectionView programmatically

Creating assortment view controllers utilizing solely Swift code requires only some further traces. You possibly can implement loadView and create your UICollectionView object there. Retailer a weak reference of it contained in the controller, and the remaining is similar.

class ViewController: UIViewController {

    weak var collectionView: UICollectionView!

    var knowledge: [Int] = Array(0..<10)

    override func loadView() {
        tremendous.loadView()

        let collectionView = UICollectionView(
            body: .zero, 
            collectionViewLayout: UICollectionViewFlowLayout()
        )
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(collectionView)
        NSLayoutConstraint.activate([
            view.topAnchor.constraint(equalTo: collectionView.topAnchor),
            view.bottomAnchor.constraint(equalTo: collectionView.bottomAnchor),
            view.leadingAnchor.constraint(equalTo: collectionView.leadingAnchor),
            view.trailingAnchor.constraint(equalTo: collectionView.trailingAnchor),
        ])
        collectionView = collectionView
    }

    override func viewDidLoad() {
        tremendous.viewDidLoad()

        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.register(Cell.self, forCellWithReuseIdentifier: Cell.identifier)
        collectionView.alwaysBounceVertical = true
        collectionView.backgroundColor = .white
    }
}

extension ViewController: UICollectionViewDataSource {

    func collectionView(
        _ collectionView: UICollectionView,
        numberOfItemsInSection part: Int
    ) -> Int {
        knowledge.depend
    }

    func collectionView(
        _ collectionView: UICollectionView,
        cellForItemAt indexPath: IndexPath
    ) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(
            withReuseIdentifier: Cell.identifier, 
            for: indexPath
        ) as! Cell

        let knowledge = knowledge[indexPath.item]
        cell.textLabel.textual content = String(knowledge)
        return cell
    }
}

extension ViewController: UICollectionViewDelegate {

    func collectionView(
        _ collectionView: UICollectionView, 
        didSelectItemAt indexPath: IndexPath
    ) {

    }
}

extension ViewController: UICollectionViewDelegateFlowLayout {

    func collectionView(
        _ collectionView: UICollectionView,
        structure collectionViewLayout: UICollectionViewLayout,
        sizeForItemAt indexPath: IndexPath
    ) -> CGSize {
        .init(width: collectionView.bounds.width, peak: 44)
    }

    func collectionView(
        _ collectionView: UICollectionView,
        structure collectionViewLayout: UICollectionViewLayout,
        insetForSectionAt part: Int
    ) -> UIEdgeInsets {
        .init(high: 0, left: 0, backside: 0, proper: 0) //.zero
    }

    func collectionView(
        _ collectionView: UICollectionView,
        structure collectionViewLayout: UICollectionViewLayout,
        minimumInteritemSpacingForSectionAt part: Int
    ) -> CGFloat {
        0
    }

    func collectionView(
        _ collectionView: UICollectionView,
        structure collectionViewLayout: UICollectionViewLayout,
        minimumLineSpacingForSectionAt part: Int
    ) -> CGFloat {
        0
    }
}

That was simple. Anchors are actually highly effective, Interface Builder is extraordinarily useful, however typically it’s simply sooner to create your views from code. The selection is yours, however please don’t be afraid of coding person interfaces! 😅

Associated posts


On this article I’ve gathered my high 10 favourite trendy UIKit suggestions that I would undoubtedly need to know earlier than I begin my subsequent mission.


Discover ways to construct complicated types with my up to date assortment view view-model framework with out the wrestle utilizing Swift.


Do you need to discover ways to load a xib file to create a customized view object? Effectively, this UIKit tutorial is only for you written in Swift.


Just a bit recommendation about creating customized view programmatically and the reality about why kind constructing with assortment views sucks.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments