在 swift 中的 UICollectionViewCell 中的 UIimage 上设置圆角

Set rounded corners on UIimage in UICollectionViewCell in swift

我有一个简单的问题,无法在 google、文档或此处找到解决方案。

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

具体来说,我知道如何创建 UIImage 的圆角。但是如果是Collectionview cell的subview,不知道在哪里设置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    
}

提前致谢!

您是否尝试过将其放入自定义 UICollectionViewCell 的初始化函数中?

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

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

好吧,您正在使用您所说的答案中的部分代码。 另一部分是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 class 中覆盖 layoutSubviews 并将代码放在那里:

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

您还可以创建如下扩展:

extension UIView {
    func addBorder(color: UIColor, cornerRadius: CGFloat = 10, borderWidth: CGFloat = 1.0) {
        layer.borderWidth = borderWidth;
        layer.borderColor = color.cgColor
        layer.cornerRadius = cornerRadius
        layer.masksToBounds = true
    }
}