2016-02-15 34 views
0

我想給一個UIImageView圓形彩色背景UICollectionViewCell。爲此,我正在將cornerRadius應用於UIImageViewlayerUIImageView在圓形背景上,在UICollectionViewCell

顯然cornerRadius需要是frame的高度/寬度的一半。我把這個代碼放在layoutSubviews方法中,這可能是錯誤的,因爲當它被稱爲圖像的frame是巨大的。旋轉手機並旋轉回來解決了問題,因爲那時frame已被正確設置。

我應該在哪裏放置cornerRadius計算代碼?

無論如何,有沒有更好的方式在圓形背景上獲取圖像?

注意:UIImageView可能會在佈局操作過程中更改高度/寬度。我正在使用Autolayout。

代碼:

class EventPickerCell: UICollectionViewCell 
{ 
    @IBOutlet weak var image: UIImageView! 
    @IBOutlet weak var label: UILabel! 

    override func layoutSubviews() 
    { 
     super.layoutSubviews() 

     print("imagesizes = frame = \(image.frame), bounds = \(image.bounds)") 
     image.layer.cornerRadius = CGRectGetWidth(image.frame)/2 
     image.layer.backgroundColor = UIColor.whiteColor().CGColor 
    } 
} 
+0

你試過'collectionView:willDisplayCell:'? –

+0

謝謝@KyleRedfearn。我寧願將代碼保留在單元格內,但不要求集合視圖涉及單元格的外觀。這就是爲什麼我最初覆蓋集合視圖單元格的原因。 – HughHughTeotl

+0

我想你將不得不使用委託和數據源。這就是他們爲 –

回答

1

你總是可以只繼承一個UIImageView以設置cornerRadiusframe更改。

class CircularImageView : UIImageView { 
    override var frame: CGRect { 
     didSet { // frame did change 
      self.layer.cornerRadius = frame.size.width*0.5 // set corner radius 
     } 
    } 
} 
+0

好的想法。鑑於細胞本身似乎缺乏控制,我認爲這是最好的解決方案。 – HughHughTeotl

-1

嘗試cellForItemAtIndexPath。

您可以將您的單元實例化爲EventPickerCell並可以訪問其所有屬性。

另一種方法是查看計算變量。

類似的規定: 您的單元格內:

var image: UIImage = UIImage() { 
    didSet { 
     imageView.image = image 
     imageView.layer.cornerRadius = image.size.width 
} 

爲您設置的細胞圖像,這將盡快設定圓角半徑。

+0

謝謝你的答案。不過,我寧願將代碼保存在單元本身中,以便我可以重新使用它。有沒有重寫'UICollectionViewCell'? – HughHughTeotl

+0

查看我的更新回答 – smnk

1

您將單元格提供給func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell中的集合視圖控制器。這是配置單元的地方,所以你也應該在這裏更新圖像層。

如果你想只是一個視圖本身要做到這一點,你可以創建一個UIImageView子類,並觀看bounds更新:

override var bounds: CGRect { 
    didSet { 
    // update layer here 
    } 
}