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 cells with circular images plus rotation support
    iOS Development

    UICollectionView cells with circular images plus rotation support

    AdminBy AdminApril 9, 2026No Comments4 Mins Read7 Views
    Facebook Twitter Pinterest LinkedIn Telegram Tumblr Email
    UICollectionView cells with circular images plus rotation support
    Share
    Facebook Twitter LinkedIn Pinterest Email


    Learn how to make rounded corners for UIImageView items wrapped inside collection view cells, with rotation support.

    Circular cells inside a collection view

    Achieving the goal is relatively easy, but if you don’t know what’s going on in the background it’s going to be harder than you would think first. So let’s create a new project add a storyboard with a UICollectionViewController, drag a UIImageView inside the cell, resize it, add some constraints, set the cell identifier.

    UICollectionView cells with circular images plus rotation support

    It should look something like the image above. Nothing special just a simple UI for our example application. Now search for some random image, add it to the project and let’s do some real coding. First I’ll show you the little trick inside of the cell subclass.

    class Cell: UICollectionViewCell {
    
        @IBOutlet weak var imageView: UIImageView!
    
        override var bounds: CGRect {
            didSet {
                layoutIfNeeded()
            }
        }
    
        override func awakeFromNib() {
            super.awakeFromNib()
    
            imageView.layer.masksToBounds = true
        }
    
        override func layoutSubviews() {
            super.layoutSubviews()
    
            setCircularImageView()
        }
    
        func setCircularImageView() {
            imageView.layer.cornerRadius = CGFloat(
                roundf(Float(imageView.frame.size.width / 2.0))
            )
        }
    }
    

    Can you see it? Yes, you should override the bounds property. As the next step we have to write the controller class with some basic data source for the collection view and with the proper support for the rotation methods. 🤓

    class ViewController: UICollectionViewController {
    
        override func collectionView(
            _ collectionView: UICollectionView,
            numberOfItemsInSection section: Int
        ) -> Int {
            30
        }
    
        override func collectionView(
            _ collectionView: UICollectionView,
            cellForItemAt indexPath: IndexPath
        ) -> UICollectionViewCell {
    
            let cell = collectionView.dequeueReusableCell(
                withReuseIdentifier: "Cell", 
                for: indexPath
            ) as! Cell
    
            cell.imageView.image = UIImage(named: "Example.jpg")
            cell.imageView.backgroundColor = .lightGray
    
            return cell
        }
    
        override func traitCollectionDidChange(
            _ previousTraitCollection: UITraitCollection?
        ) {
            super.traitCollectionDidChange(previousTraitCollection)
    
            guard
                let previousTraitCollection = previousTraitCollection,
                traitCollection.verticalSizeClass != previousTraitCollection.verticalSizeClass ||
                traitCollection.horizontalSizeClass != previousTraitCollection.horizontalSizeClass
            else {
                return
            }
    
            collectionView?.collectionViewLayout.invalidateLayout()
            collectionView?.reloadData()
        }
    
        override func viewWillTransition(
            to size: CGSize, 
            with coordinator: UIViewControllerTransitionCoordinator
        ) {
            super.viewWillTransition(to: size, with: coordinator)
    
            collectionView?.collectionViewLayout.invalidateLayout()
    
            coordinator.animate(alongsideTransition: { context in
    
            }, completion: { context in
                collectionView?.collectionViewLayout.invalidateLayout()
    
                collectionView?.visibleCells.forEach { cell in
                    guard let cell = cell as? Cell else {
                        return
                    }
                    cell.setCircularImageView()
                }
            })
        }
    }
    
    extension ViewController: UICollectionViewDelegateFlowLayout {
    
        func collectionView(
            _ collectionView: UICollectionView,
            layout collectionViewLayout: UICollectionViewLayout,
            sizeForItemAt indexPath: IndexPath
        ) -> CGSize {
            .init(
                width: collectionView.frame.size.width/3.0 - 8,
                height: collectionView.frame.size.width/3.0 - 8
            )
        }
    }
    

    If you are familiar with collection views, you might ask why am I doing this tutorial? It’s so simple. It just works, right? No, actually without the overridden bounds property the example would look something like this on the left side. 😢

    Circular images

    Funny, huh? The image on the right side is the actual result with the overridden bounds, that’s the expected behavior. Scrolling and rotation is going to be really strange if you don’t override bounds and you don’t reset the cornerRadius property for the visible views. You might ask: but why? 🤔

    Layers, springs & struts and some explanation

    Apple still has “Springs & Struts” based code inside of UIKit. This means that frame and bound calculations are happening in the underlying system and the constraint system is trying to work hard as well to figure out the proper measures.

    “Springs & Struts” needs to die!

    While there is an init(frame:) method, or a required init(coder:) these layout things will suck as hell. I really like Interface Builder, but until we can not get a fine tool to create great user interfaces IB is going to be just another layer of possible bugs.

    This issue won’t even be there if you create the cell from code only using auto layout constraints or layout anchors! It’s because IB creates the cell based on the frame you gave in while you designed your prototype. But if you forget init(frame:) and you just create a new UIImageView instance and let auto layout do the hard work, the layout system will solve everything else. Check this.

    class Cell: UICollectionViewCell {
    
        weak var imageView: UIImageView!
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    
        override init(frame: CGRect) {
            super.init(frame: frame)
    
            translatesAutoresizingMaskIntoConstraints = false
    
            let imageView = UIImageView()
            imageView.translatesAutoresizingMaskIntoConstraints = false
            addSubview(imageView)
            imageView = imageView
    
            imageView.topAnchor.constraint(equalTo: topAnchor)
            imageView.bottomAnchor.constraint(equalTo: bottomAnchor)
            imageView.leadingAnchor.constraint(equalTo: leadingAnchor)
            imageView.trailingAnchor.constraint(equalTo: trailingAnchor)
        }
    
        override func layoutSubviews() {
            super.layoutSubviews()
    
            imageView.layer.masksToBounds = true
            imageView.layer.cornerRadius = CGFloat(
                roundf(Float(imageView.frame.size.width/2.0))
            )
        }
    }
    

    Obviously you have to write more code, register your cell class manually inside the controller class and you also have to override the layoutSubviews method inside the cell, but it’ll work as it is expected. 🙄

    collectionView?.register(Cell.self, forCellWithReuseIdentifier: "Cell")
    

    Anyway, after you register the programmatically created cell you’ll have a nice way of displaying circular images. Using this technique is quite tricky, but it definitely works in every case. You can download the example from The.Swift.Dev. tutorials on GitHub.



    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, 202577 Views

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

    May 16, 202642 Views

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

    April 9, 202641 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.