按钮

时间:2017-11-16 17:05:03

标签: ios swift uicollectionview

我正在使用UICollectionView,我正在考虑如何为每个集合视图单元格添加按钮,我不希望所有按钮都执行相同的操作。我需要更改按钮操作。我不知道该怎么做。

import UIKit

class FirstARViewController: UIViewController , UICollectionViewDelegate , UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {


    @IBOutlet weak var collectionView: UICollectionView!
    var imagescv = ["cv1","cv2","cv3","cv4","cv5"]

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView.delegate = self
        collectionView.dataSource = self
    }

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

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! cellimagesar

        cell.layer.cornerRadius = 5

        cell.layer.borderWidth = 1

        cell.myImages.image = UIImage(named: imagescv [indexPath.row])
        cell.myImages.contentMode = .scaleToFill
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 182, height: 290)
    }
}

1 个答案:

答案 0 :(得分:0)

tagaction分配到collectionviewcell内的按钮。 将indexPath.item指定为按钮标记是从单元格数中标识特定按钮的最佳方法。 您需要在cellForItemAt委托方法中执行所有操作。

cell.btnCounter.tag = indexPath.item
cell.btnCounter.addTarget(self, action: #selector(self.buttonClicked), for: .touchUpInside)

现在你只需处理如下事件

func buttonClicked(_ sender: UIButton) {
        //Here sender.tag will give you the tapped Button index from the cell
        //You can identify the button from the tag  
    }