ios - 带按钮的 UICollectionView

标签 ios swift uicollectionview

我正在使用 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/

相关文章:

swift - String.withCString() 的函数输入是什么类型?

swift - 类似日历的 UICollectionView - 如何仅在第一项之前添加左插图?

ios - 在 View Controller 中添加 UICollectionview

objective-c - 尝试在 XCode 中将数据 Controller 分配给 UICollectionViewController 时出现错误

ios - react-native - TouchableWithoutFeedback 与 ScrollView

objective-c - MKMapView 中的奇怪行为 - 引脚消失

android - 带有操作按钮和图像的 Flutter 本地通知

iphone - 为较旧的 SDK 部署 iOS 应用程序时,如何测试它?

ios - UIScrollView - UILabel 如何将内容推到屏幕外

swift - 类型 'Background.Type' 不能符合 'View' ;只有结构/枚举/类类型 SwiftUI