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

Jel*_*l92 13 uiimage viewcontroller collectionview ios 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
    }
Run Code Online (Sandbox Code Playgroud)

并在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    
}
Run Code Online (Sandbox Code Playgroud)

提前致谢!

Sam*_*m_M 21

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

更新你awakeFromNib喜欢这个:

override func awakeFromNib() {
    mImage.layer.cornerRadius = 5 
    mimage.clipsToBounds = true
}
Run Code Online (Sandbox Code Playgroud)

要使其成为圆形,您需要将cornerRadius设置为方形高度的一半.在你cellForItemAtIndexPath添加这些行:

cell.layoutIfNeeded()
cell.mImage.layer.cornerRadius = cell.mImage.frame.height/2
Run Code Online (Sandbox Code Playgroud)

更新

为了避免layoutSubviews被调用两次,layoutSubviewsDescriptionCell类中重写并将代码放在那里:

override func layoutSubviews() {
    super.layoutSubviews()
    layoutIfNeeded()
    mImage.layer.cornerRadius = mImage.frame.height/2
}
Run Code Online (Sandbox Code Playgroud)

  • 在调用`awakeFromNib`之后,需要将角半径设置为基于帧.在确定单元格大小并设置图像后,需要完成此操作. (2认同)