繁体   English   中英

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

[英]Set rounded corners on UIimage in UICollectionViewCell in swift

我有一个简单的问题,我无法在谷歌,文档或这里找到解决方案。

我的视图控制器中有一个Collectionview。 我创建了一个包含UIImage的自定义单元格DescriptionCell。 我希望这个图像有圆角。 但是,我不知道在UIImage层上设置cornerradius的位置。 我已尝试在单元格的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    
}

提前致谢!

那么你正在使用你说你正在使用的答案中的部分代码。 另一部分是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
}

您是否尝试将其置于自定义UICollectionViewCell的init函数中?

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

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

您还可以创建一个扩展名,如:

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
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM