如何在UICollection View单元中显示图像,同时单击swift ios中的单元格?

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! PlaceCollectionViewCell //let imageView = UIImageView() //cell.backgroundColor = UIColor(colorLiteralRed: 0.278, green: 0.694, blue: 0.537, alpha: 1.00) cell.layer.borderWidth = 0.5 cell.layer.borderColor = UIColor(colorLiteralRed: 0.278, green: 0.694, blue: 0.537, alpha: 1.00).cgColor //cell.placeLabel.tintColor = UIColor(colorLiteralRed: 0.278, green: 0.694, blue: 0.537, alpha: 1.00).cgColor cell.layer.cornerRadius = 40 cell.layer.masksToBounds = true print("places\(indexPath.row)") //cell.placeLabel.text = places[indexPath.row] as! String cell.placeLabel.text = places[indexPath.row] cell.placeLabel.textColor = UIColor(colorLiteralRed: 0.278, green: 0.694, blue: 0.537, alpha: 1.00) // code for VIew let view = UIView(frame: cell.bounds) //Set background color that you want view.backgroundColor = UIColor(colorLiteralRed: 0.278, green: 0.694, blue: 0.537, alpha: 1.00) cell.selectedBackgroundView = view return cell 

我有一个收集视图单元格中的图像。 我只需要单击单元格时显示该图像。我们必须在cellforRowat索引path中执行此操作吗?

 //Custom class code: @IBOutlet weak var tickImageView: UIImageView! @IBOutlet weak var placeViewBtn: UIButton! @IBOutlet weak var placeLabel: UILabel! @IBOutlet weak var imageView: UIImageView! override func layoutSubviews() { } override func awakeFromNib() { self.imageView.layer.cornerRadius = self.imageView.frame.size.width/2 self.imageView.layer.masksToBounds = true super.awakeFromNib() // Initialization code } 

自定义类代码添加。 我想要显示上面已经声明的ticMark图像。

声明IndexPathtypes的一个实例,并保持它所selected的单元格状态。 现在在这个cellForItemAt indexPathdidSelectItemAt indexPath使用这个数组。

 var selectedIndexPaths = IndexPath() func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! PlaceCollectionViewCell //Your code //decide weather to show tick image or not self.tickImageView.isHidden = self.selectedIndexPaths != indexPath } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if self.selectedIndexPaths == indexPath { self.selectedIndexPaths = IndexPath() } else { self.selectedIndexPaths = indexPath } self.tableview.reloadData() } 

您需要阅读更多的select,或不在cellForRow中

如果select了勾号{showImage} else {hideImage}

然后在didSelectRow中设置勾选或取消选中,然后调用reloadRowForIndexPath