我需要联系我的馆藏视图中的一个具体单元格而不点击它。例如,我需要更改第二个单元格中图像的颜色并使其变黑。你知道任何解决方案吗?
这是一张图片:
这是我的代码:
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
}
}
答案 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
}
}