Reputation: 2259
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
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
Does anyone have any Idea about this issue. Thanks in advance.
Upvotes: 1
Views: 4029
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
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
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