我正在使用 UICollectionView
并且我正在考虑如何为每个 Collection View 单元格添加按钮,并且我不希望所有按钮都执行相同的操作。我需要更改按钮操作。我不知道该怎么做。
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)
}
}
最佳答案
将标签
和操作
分配给collectionviewcell
内的按钮。
将 indexPath.item
分配为按钮标签是从单元格数量中识别特定按钮的最佳方法。
您需要在 cellForItemAt
委托(delegate)方法中完成所有操作。
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
}
关于ios - 带按钮的 UICollectionView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47335367/