2016-09-30 100 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 
}