2016-07-07 93 views
2

我有幾個屬性的自定義UICollectionViewCell類:在自定義到的UIImageView添加覆蓋UICollectionViewCell

class SimpleCollectionCell: UICollectionViewCell { 

    @IBOutlet weak var title_more: UILabel! 

    @IBOutlet weak var image_more: UIImageView! 

    @IBOutlet weak var title: UILabel! 

    @IBOutlet weak var distance: UILabel! 

    @IBOutlet weak var activity: UIImageView! 

} 

我來填充數據的方法是這樣:

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { 

    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! SimpleCollectionCell 

    var place = Place() 

    // set the current place 
    place = Places[indexPath.row] 

    // set the label 
    cell.title.text = place.title 

    // setup url 
    let url = NSURL(string: currentThing.imageUrl!) 

    // set the cell image 
    cell.activity.hnk_setImageFromURL(url!) 

    return cell 

} 

細胞呈現爲它應該與顯示爲這樣:

UICollectionViewCells

我的問題是如何讓圖像變暗?

我試圖添加下面的代碼在cellForItemAtIndexPath方法的底部,但它會變得越來越黑,因爲它不斷添加更多的子視圖!

// Create a subview which will add an overlay effect on image view 
let overlay: UIView = UIView(frame: CGRectMake(0, 0, cell.activity.frame.size.width, cell.activity.frame.size.height)) 
    overlay.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.3); 

// Add the subview to the UIImageView 
cell.activity.addSubview(overlay) 
+0

爲什麼不從xib文件創建單元格並在其中添加疊加視圖? – Remover

回答

3

一個快速解決方案是檢查是否已經添加疊加到單元格,如果沒有添加另一個。

使用標籤:

if cell.activity.viewWithTag(99) == nil { 
    // Create a subview which will add an overlay effect on image view 
    let overlay = UIView(frame: CGRect(x: 0, y: 0, width: cell.frame.size.width, height: cell.frame.size.height)) 
    overlay.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.3); 
    overlay.tag = 99 

    // Add the subview to the UIImageView 
    cell.activity.addSubview(overlay) 
} 

或者剛剛從單元格中創建的覆蓋。

相關問題