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.
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.
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.