Ios 带按钮的UICollectionView
我使用的是Ios 带按钮的UICollectionView,ios,swift,uicollectionview,Ios,Swift,Uicollectionview,我使用的是UICollectionView,我正在考虑如何为每个集合视图单元格添加按钮,我不希望所有按钮都执行相同的操作。我需要更改按钮操作。我不知道怎么做 import UIKit class FirstARViewController: UIViewController , UICollectionViewDelegate , UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { @IBOutlet w
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)
}
}
将
标记
和操作
分配给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
}
可能重复“我不希望所有按钮都执行相同的操作”您希望在按钮上更改哪种操作@Faisal@Faisal我想在这种情况下,您需要为每个按钮提供标记值,并对不同的按钮执行不同的操作cell@Maddyヅヅ 我有20个按钮,如果你知道如何把它们都作为动作来做我想做的事情,我只需要知道如何添加按钮ok,但是我可以在哪里添加按钮动作,如果你可以这样使用它,你能给我一个例子吗否则如果(sender.tag==1){print(“no”)}就好了?