Teena nath Paul
Teena nath Paul

Reputation: 2259

Corner radius of a UIButton in UICollectionViewCell not working

I have a UICollectionView in a ViewController of type ANY-ANY storyboard and using auto-layout with swift. I have changed the size of ViewController to iPhone 5 screen size.

The problem is that, there is a button inside the UICollectionViewCell and I am trying to make that circular. When I run in iPhone 5 the button gets in circular fine, But if I run in iPhone 6 or 6+ it doesn't come in circular.

Below is the code i am using in "cellForItemAtIndexPath"

    var btnImage = cell.contentView.viewWithTag(100) as UIButton
    btnImage.layer.masksToBounds = true
    btnImage.layer.cornerRadius = btnImage.frame.size.height/2

The result of this code is as below enter image description here

And if I use below code

    var btnImage = cell.contentView.viewWithTag(100) as UIButton
    btnImage.layoutIfNeeded()
    btnImage.layer.masksToBounds = true
    btnImage.layer.cornerRadius = btnImage.frame.size.height/2

The result is as below

enter image description here

Does anyone have any Idea about this issue. Thanks in advance.

Upvotes: 1

Views: 4029

Answers (3)

Teena nath Paul
Teena nath Paul

Reputation: 2259

The solution that worked for this issue is below:

cell.contentView.frame = cell.bounds //This is important line
var btnImage = cell.contentView.viewWithTag(100) as UIButton
btnImage.layoutIfNeeded() //This is important line
btnImage.layer.masksToBounds = true
btnImage.layer.cornerRadius = btnImage.frame.size.height/2

Above code makes the button complete circular.

Upvotes: 9

Shubhi
Shubhi

Reputation: 73

This is due to autolayout constraint. As the height and width can increased after corner radius size is set.Try to set this in storyboard.

Upvotes: 1

rptwsthi
rptwsthi

Reputation: 10172

Roundrect not working with collection view cell can not be the case. I have just created a demo application to test that and it works. Below is code from my demo.

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    var cell:CollectionCell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CollectionCell

    // Configure the cell
    cell.roundTestButton.layer.cornerRadius = 10.0
    cell.roundTestButton.layer.masksToBounds = true

    println(cell.roundTestButton)

    return cell
}

Or here is git link of complete project.

Upvotes: 1

Related Questions