UICollectionViewCell中UIButton的拐角半径不起作用

问题描述:

我在ViewController中有一个UICollectionView类型为ANY-ANY故事板,并使用swift自动布局。我已将ViewController的大小更改为iPhone 5屏幕大小。UICollectionViewCell中UIButton的拐角半径不起作用

问题是,UICollectionViewCell中有一个按钮,我正在尝试制作该通告。当我在iPhone 5中运行时,按钮的通道很好,但是如果我在iPhone 6或6+上运行,它不会循环显示。

下面是我使用 “cellForItemAtIndexPath” 代码

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

这段代码的结果如下 enter image description here

如果我用下面的代码

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

的结果如下

enter image description here

有没有人有关于这个问题的任何想法。 在此先感谢。

,对于这个问题的工作方案是如下:

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 

上面的代码使按钮完整的圆形。

Roundrect不能使用集合视图单元格不能这样。我刚刚创建了一个演示应用程序来测试它,它工作。以下是我演示的代码。

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 
} 

here is git link的完整项目。

+0

我想让按钮完成循环。我从git下载了你的代码,并用“cell.roundTestButton.layer.cornerRadius = cell.roundTestButton.frame.size.height/2 ” 替换了这行代码,并在iPhone 6+上运行,并且这不是完整的循环,而是变成了椭圆。 –

+0

@TeenanathPaul我没有将它制作成循环我只是确保圆形矩形在UICollectionViewCell上工作得很好。 – rptwsthi

+0

感谢@ rptwsthi,我得到了解决方案,并且按钮现在已完成循环。 –

这是由于自动布局约束。由于角落半径大小设置后可以增加高度和宽度。请尝试在故事板中设置此值。