swift集合视图:如何更改某个特定单元格的图像视图颜色?

时间:2017-04-08 06:14:57

标签: swift uicollectionview uicollectionviewcell

我需要联系我的馆藏视图中的一个具体单元格而不点击它。例如,我需要更改第二个单元格中图像的颜色并使其变黑。你知道任何解决方案吗?

这是一张图片:

enter image description here

这是我的代码:

import UIKit


class SimplestCollectionViewCell: UICollectionViewCell {

var sImageView: UIImageView!

override func awakeFromNib() {



    sImageView = UIImageView(frame: contentView.frame)
    sImageView.contentMode = .scaleToFill
    sImageView.clipsToBounds = true


    let sImage = UIImage(named: "banana.png")?.withRenderingMode(.alwaysTemplate)
    sImageView.image = sImage
    sImageView.tintColor = UIColor.orange

    contentView.addSubview(sImageView)

    }


}

extension ViewController: UICollectionViewDelegate,     UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 49
}

// we use this method to dequeue the cell and set it up
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "sCell", for: indexPath) as! SimplestCollectionViewCell
    cell.awakeFromNib()
    return cell
}

}

更新:建议代码中的编译器错误: enter image description here

1 个答案:

答案 0 :(得分:0)

import UIKit

class SimplestCollectionViewCell: UICollectionViewCell {

var sImageView: UIImageView!
var shouldCellBeBlack: Bool = false//give any suitable name you like
override func awakeFromNib() {



sImageView = UIImageView(frame: contentView.frame)
sImageView.contentMode = .scaleToFill
sImageView.clipsToBounds = true


let sImage = UIImage(named: "banana.png")?.withRenderingMode(.alwaysTemplate)
sImageView.image = sImage

sImageView.tintColor  = shouldCellBeBlack ? UIColor.black :  UIColor.orange

contentView.addSubview(sImageView)

}


}

extension ViewController: UICollectionViewDelegate,     UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 49
}

// we use this method to dequeue the cell and set it up
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "sCell", for: indexPath) as! SimplestCollectionViewCell
    if indexPath.row == 2 //set the value of the cell whose image you want to make black {
      cell.shouldCellBeBlack = true
    }else {
      cell.shouldCellBeBlack = false
    }
    cell.awakeFromNib()
    return cell
}
}