2016-09-30 101 views
12

我有一个简单的问题,我找不到解决方案在谷歌,文档或这里。在UICollectionViewCell中的UIimage在swift中设置圆角

我在我的视图控制器中有一个CollectionView。我创建了一个包含UIImage的自定义单元DescriptionCell。我希望这个图像有圆角。但是,我不知道在UIImage图层上设置角点的位置。我试过在单元的awakeFromNib方法中,在委托方法CellForRowAtIndexPath中并覆盖单元格中的LayoutSubview,但它不起作用。 我应该在哪里设置UIImage的半径代码?

要指定,我知道如何创建UIImage的圆角。但如果它是一个Collectionview单元格的子视图,我不知道在哪里设置cornerradius。

这里是代码为我descriptionCell

class DescriptionCell: UICollectionViewCell { 
    @IBOutlet weak var mImage: UIImageView! 

    override func awakeFromNib() { 
    //mImage.layer.cornerradius = 5 
    //Does not work, the image is still square in the cell 
    } 

而在cellforRowAtIndePath

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { 
var cell = collectionView.dequeueReusableCellWithReuseIdentifier("descriptioncell", forIndexPath: indexPath) as! DescriptionCell 
    //cell.mImage.layer.cornerradius = 5 
    //Does not work, the image is still square in the cell 
return cell  
} 

提前感谢!

+2

的可能的复制[为UIImage制作圆角](http://stackoverflow.com/questions/8938800/making-round-corners-for-a-uiimage) – Hama

+0

不,这是不同的。我已经在使用该答案中的代码。我的问题是在哪里把UIImage.layer.cornerradius = xxx? – Jell92

+0

用相关代码更新您的问题。 – rmaddy

回答

15

那么你正在使用你说你使用的答案的代码的一部分。 另一部分是imageView.clipsToBounds = true

更新您的awakeFromNib这样的:

override func awakeFromNib() { 
    mImage.layer.cornerRadius = 5 
    mimage.clipsToBounds = true 
} 

为了它,你需要cornerRadius设置为方高度半圈。在您的cellForItemAtIndexPath加上这些行:

cell.layoutIfNeeded() 
cell.mImage.layer.cornerRadius = cell.mImage.frame.height/2 

更新

为了避免被调用两次layoutSubviews,在DescriptionCell类中重写layoutSubviews,并把那里的代码:

override func layoutSubviews() { 
    super.layoutSubviews() 
    layoutIfNeeded() 
    mImage.layer.cornerRadius = mImage.frame.height/2 
} 
+0

我认为这是诀窍!然而,现在又出现了另一个问题,我希望它是圆形的。我知道代码是这样的:mImage.layer.cornerRadius = mImage.frame.width/2但是,当我使用它不起作用。图像消失了! – Jell92

+2

在调用'awakeFromNib'之后,需要大量设置基于框架的角半径。它需要在单元格大小和图像设置完成后完成。 – rmaddy

+0

感谢您的回答!那究竟是什么时候?那么我可以用什么方法设置它? – Jell92

1

你有没有试过把它放在自定义UICollectionViewCell的init函数中?

override init(frame: CGRect) { 
    super.init(frame: frame) 

    image.layer.masksToBounds = true 
    image.layer.cornerRadius = 10 
}