Swift : How to set Custom UICollectionViewCell as circle?

12,713

Solution 1

This is my UICollectionView Example which you can check for your solution. I am using storyboard to setup the primary collectionView with AutoLayout. Also, attaching some screenshots to clarify the result.

There is a method called drawRect(). You can use that inside your collectionView Cell class for doing the UI stuffs.

Now here is my code.

1. ViewController.swift //Just the normal UIViewController like yours, nothing else... :)

//
//  ViewController.swift
//  CollectionCheckCircle
//
//  Created by Tuhin Samui on 02/09/16.
//  Copyright © 2016 Tuhin Samui. All rights reserved.
//

import UIKit

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

    @IBOutlet weak var collectionView: UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView.delegate = self
        collectionView.dataSource = self
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 200
    }


    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cellOfCollection = collectionView.dequeueReusableCellWithReuseIdentifier("cellCollectionView", forIndexPath: indexPath) as! CollectionViewCell

        return cellOfCollection
    }

}

2. CollectionViewCell.swift //Just a UICollectionViewCell class for dequeuing the cell.

//
//  CollectionViewCell.swift
//  CollectionCheckCircle
//
//  Created by Tuhin Samui on 02/09/16.
//  Copyright © 2016 Tuhin Samui. All rights reserved.
//

import UIKit

class CollectionViewCell: UICollectionViewCell {
    @IBOutlet weak var imageView: UIImageView!

    override func drawRect(rect: CGRect) { //Your code should go here.
        super.drawRect(rect)
        self.layer.cornerRadius = self.frame.size.width / 2
    }

}

Note: I am not using either any flowlayout of UICollectionViewFlowLayout or cell size inside sizeForItemAtIndexPath for this collectionView. You can add those things too. Please do some experiments as per your needs. BTW I am using Xcode 7.3.1 and Swift 2.2.

Here is the storyboard screenshot for collectionView setup and result on the simulator. First Storyboard screenshot with simulator result

Second Storyboard screenshot with simulator result

Hope this helped. Sorry for any mistake.

Solution 2

Just try to give corner radius as height/2, make sure cell should have same height and width.

cell.layer.cornerRadius = min(cell.frame.size.height, cell.frame.size.width) / 2.0

cell.layer.masksToBounds = true

Please, let me know if this works for you.

Solution 3

By giving this line for calculating the height of your cell

return CGSize(width: (self.objKeypadCollectionView.frame.size.width/3)-10, height: (self.objKeypadCollectionView.frame.size.height/4)-10)

You cant achieve what you want. Use Aspect Ratio technique. For Height and width of cell use your screen width and based on that aspect ratio update your cell height and width then and only then this line works....

If you need clarification skype me iammubin38

Solution 4

The problem is cell's width and height is changed at run time according to your screen width, So to solve this issue add one square UIView inside your cell and use that UIView inside cellForItemAtIndexPath method to make it circle view like this.

objKeypadCollectionViewCell.circleView.layer.borderColor = UIColor.lightGrayColor().CGColor
objKeypadCollectionViewCell.circleView.layer.borderWidth = 1
objKeypadCollectionViewCell.circleView.layer.cornerRadius = objKeypadCollectionViewCell.frame.size.width/2
objKeypadCollectionViewCell.circleView.layer.masksToBounds = true

Solution 5

Use this updated cell.

class KeypadCollectionViewCell: UICollectionViewCell {

    var circularBGLayer: CALayer!

    override func awakeFromNib() {
        super.awakeFromNib()
        backgroundColor = UIColor.clearColor()
        circularBGLayer = CALayer()
        circularBGLayer.backgroundColor = UIColor.lightGrayColor().CGColor
        layer.addSublayer(circularBGLayer)
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        var frame = self.bounds
        frame.size.width = min(frame.width, frame.height)
        frame.size.height = frame.width
        circularBGLayer.bounds = frame
        circularBGLayer.cornerRadius = frame.width*0.5
        circularBGLayer.position = CGPoint(x: frame.midX, y: frame.midY)
    }
}
Share:
12,713
Jayprakash Dubey
Author by

Jayprakash Dubey

Blog : http://jayprakashdubey.blogspot.in LinkedIn : http://in.linkedin.com/in/jpdubey Tweet : @JayprakashDube2

Updated on October 15, 2022

Comments

  • Jayprakash Dubey
    Jayprakash Dubey over 1 year

    I've custom UICollectionViewCell that contains UILabel and UIImage. I want to set the cell in circular format.

    Note:- sizeForItemAtIndexPath cannot be changed due to AutoLayout.

    Below is code that I've used :

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,sizeForItemAtIndexPath indexPath:NSIndexPath ) -> CGSize {
    
              return CGSize(width: (self.objKeypadCollectionView.frame.size.width/3)-10, height: (self.objKeypadCollectionView.frame.size.height/4)-10)
        }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    
            let objKeypadCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("idKeypadCollectionViewCell", forIndexPath: indexPath) as! KeypadCollectionViewCell
    
            if (self.numberArray[indexPath.item])=="asda" {
                objKeypadCollectionViewCell.lblNumber.text = ""
                objKeypadCollectionViewCell.imgPrint.hidden = false
            }
            else if (self.numberArray[indexPath.item])=="Derterel" {
                objKeypadCollectionViewCell.lblNumber.text = self.numberArray[indexPath.item]
                objKeypadCollectionViewCell.imgPrint.hidden = true
            }
            else {
                objKeypadCollectionViewCell.imgPrint.hidden = true
                objKeypadCollectionViewCell.lblNumber.text = self.numberArray[indexPath.item]
                objKeypadCollectionViewCell.layer.borderColor = UIColor.lightGrayColor().CGColor
                objKeypadCollectionViewCell.layer.borderWidth = 1
                objKeypadCollectionViewCell.layer.cornerRadius = objKeypadCollectionViewCell.frame.size.width/2
            }
            return objKeypadCollectionViewCell
        }
    

    Screenshot 1

    Design screen

  • Jayprakash Dubey
    Jayprakash Dubey over 7 years
    Height and Width are generated programmatically. It varies depending on device size
  • Sanoj Kashyap
    Sanoj Kashyap over 7 years
    then min fun will be taking care. Please, check and let me know.
  • Jayprakash Dubey
    Jayprakash Dubey over 7 years
    This is not working. It shows elliptical shape instead of circle.
  • Sanoj Kashyap
    Sanoj Kashyap over 7 years
    then your view must be in square. Now you can add another view on cell and make that as circle with same solution.
  • Aisha
    Aisha about 3 years
    drawRect method is the key here.