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

时间:2016-12-15 09:02:24

标签: ios uicollectionview swift3

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索引路径中执行此操作?

//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图像。

2 个答案:

答案 0 :(得分:2)

声明一个类型为IndexPath的实例,并保持单元格状态为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()
}

答案 1 :(得分:1)

你需要阅读在cellForRow中选择或不选择刻度线

如果选择了勾选{     showImage } else {     hideImage }

然后在didSelectRow中 将刻度设置为选中或取消选择 然后调用reloadRowForIndexPath