Close Menu
geekfence.comgeekfence.com
    What's Hot

    Wilkie refers gambling concerns to anti-corruption commission

    August 13, 2026

    Lumen ready for AI traffic rush – with programmable fabric and “more fiber than anyone”

    August 13, 2026

    With a feel for physics, AI models simulate a wider range of real-world scenarios | MIT News

    August 13, 2026
    Facebook X (Twitter) Instagram
    • About Us
    • Contact Us
    Facebook Instagram
    geekfence.comgeekfence.com
    • Home
    • UK Tech News
    • AI
    • Big Data
    • Cyber Security
      • Cloud Computing
      • iOS Development
    • IoT
    • Mobile
    • Software
      • Software Development
      • Software Engineering
    • Technology
      • Green Technology
      • Nanotechnology
    • Telecom
    geekfence.comgeekfence.com
    Home»iOS Development»UICollectionView data source and delegates programmatically
    iOS Development

    UICollectionView data source and delegates programmatically

    AdminBy AdminFebruary 4, 2026No Comments3 Mins Read6 Views
    Facebook Twitter Pinterest LinkedIn Telegram Tumblr Email
    UICollectionView data source and delegates programmatically
    Share
    Facebook Twitter LinkedIn Pinterest Email


    6/26/18 2:20 PM
    · 1 min read


    In this quick UIKit tutorial I’ll show you how to create a simple UICollectionView without Interface Builder, but only using Swift.

    UICollectionViewCell programmatically

    If you’d like to add views to your cell, you should use the init(frame:) method, and set up your view hierarchy there. Instead of awakeFromNib you should style your views in the init method as well. You can reset everything inside the usual prepareForReuse method. As you can see by using anchors sometimes it’s worth to ditch IB entirely. 🎉

    class Cell: UICollectionViewCell {
    
        static var identifier: String = "Cell"
    
        weak var textLabel: UILabel!
    
        override init(frame: CGRect) {
            super.init(frame: frame)
    
            let textLabel = UILabel(frame: .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 implemented")
        }
    
        override func prepareForReuse() {
            super.prepareForReuse()
            
            reset()
        }
    
        func reset() {
            textLabel.textAlignment = .center
        }
    }
    

    UICollectionView programmatically

    Creating collection view controllers using only Swift code requires only a few additional lines. You can implement loadView and create your UICollectionView object there. Store a weak reference of it inside the controller, and the rest is the same.

    class ViewController: UIViewController {
    
        weak var collectionView: UICollectionView!
    
        var data: [Int] = Array(0..<10)
    
        override func loadView() {
            super.loadView()
    
            let collectionView = UICollectionView(
                frame: .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() {
            super.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 section: Int
        ) -> Int {
            data.count
        }
    
        func collectionView(
            _ collectionView: UICollectionView,
            cellForItemAt indexPath: IndexPath
        ) -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCell(
                withReuseIdentifier: Cell.identifier, 
                for: indexPath
            ) as! Cell
    
            let data = data[indexPath.item]
            cell.textLabel.text = String(data)
            return cell
        }
    }
    
    extension ViewController: UICollectionViewDelegate {
    
        func collectionView(
            _ collectionView: UICollectionView, 
            didSelectItemAt indexPath: IndexPath
        ) {
    
        }
    }
    
    extension ViewController: UICollectionViewDelegateFlowLayout {
    
        func collectionView(
            _ collectionView: UICollectionView,
            layout collectionViewLayout: UICollectionViewLayout,
            sizeForItemAt indexPath: IndexPath
        ) -> CGSize {
            .init(width: collectionView.bounds.width, height: 44)
        }
    
        func collectionView(
            _ collectionView: UICollectionView,
            layout collectionViewLayout: UICollectionViewLayout,
            insetForSectionAt section: Int
        ) -> UIEdgeInsets {
            .init(top: 0, left: 0, bottom: 0, right: 0) //.zero
        }
    
        func collectionView(
            _ collectionView: UICollectionView,
            layout collectionViewLayout: UICollectionViewLayout,
            minimumInteritemSpacingForSectionAt section: Int
        ) -> CGFloat {
            0
        }
    
        func collectionView(
            _ collectionView: UICollectionView,
            layout collectionViewLayout: UICollectionViewLayout,
            minimumLineSpacingForSectionAt section: Int
        ) -> CGFloat {
            0
        }
    }
    

    That was easy. Anchors are really powerful, Interface Builder is extremely helpful, but sometimes it’s just faster to create your views from code. The choice is yours, but please don’t be afraid of coding user interfaces! 😅


    UICollectionView data source and delegates programmatically

    Share this article

    Thank you. 🙏

    Related posts

    UICollectionView data source and delegates programmatically

    2/3/22 3:20 PM
    · 8 min read


    In this article I’ve gathered my top 10 favorite modern UIKit tips that I’d definitely want to know before I start my next project.

    UICollectionView data source and delegates programmatically

    5/23/19 2:20 PM
    · 5 min read


    Learn how to build complex forms with my updated collection view view-model framework without the struggle using Swift.

    UICollectionView data source and delegates programmatically

    10/16/18 2:20 PM
    · 5 min read


    Do you want to learn how to load a xib file to create a custom view object? Well, this UIKit tutorial is just for you written in Swift.

    UICollectionView data source and delegates programmatically

    10/21/19 2:20 PM
    · 4 min read


    Just a little advice about creating custom view programmatically and the truth about why form building with collection views sucks.



    Source link

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email

    Related Posts

    What’s New in Xcode 27

    July 30, 2026

    ios – iCloud Dashboard returns “Internal Error” when querying records across all containers

    July 27, 2026

    ios – How to resolve the “Failed to build cache” build error in Xcode on macOS running in Docker in the docurr/macos project?

    July 22, 2026

    ios – Do Critical Alert (Apple) sounds play one at a time, or can two overlap?

    July 17, 2026

    ios – Bizarre animation issue in SwiftUI

    July 12, 2026

    security – How and where mnemonic/private keys are generated/stored in IOS for mobile non-custodial wallet

    July 7, 2026
    Top Posts

    Understanding U-Net Architecture in Deep Learning

    November 25, 202585 Views

    The Next Paradigm in Efficient Inference Scaling – The Berkeley Artificial Intelligence Research Blog

    May 16, 202648 Views

    Is it too late to start learning AI and machine learning in my 30s or 40s?

    April 9, 202648 Views
    Don't Miss

    Wilkie refers gambling concerns to anti-corruption commission

    August 13, 2026

    Independent MP Andrew Wilkie has taken the fight over gambling reform to the National Anti-Corruption…

    Lumen ready for AI traffic rush – with programmable fabric and “more fiber than anyone”

    August 13, 2026

    With a feel for physics, AI models simulate a wider range of real-world scenarios | MIT News

    August 13, 2026

    Monitoring beyond SNMP: Turning your network into a sensor

    August 13, 2026
    Stay In Touch
    • Facebook
    • Instagram
    About Us

    At GeekFence, we are a team of tech-enthusiasts, industry watchers and content creators who believe that technology isn’t just about gadgets—it’s about how innovation transforms our lives, work and society. We’ve come together to build a place where readers, thinkers and industry insiders can converge to explore what’s next in tech.

    Our Picks

    Wilkie refers gambling concerns to anti-corruption commission

    August 13, 2026

    Lumen ready for AI traffic rush – with programmable fabric and “more fiber than anyone”

    August 13, 2026

    Subscribe to Updates

    Please enable JavaScript in your browser to complete this form.
    Loading
    • About Us
    • Contact Us
    • Disclaimer
    • Privacy Policy
    • Terms and Conditions
    © 2026 Geekfence.All Rigt Reserved.

    Type above and press Enter to search. Press Esc to cancel.