【问题标题】:UICollectionView custom button actions in Swift 3Swift 3 中的 UICollectionView 自定义按钮操作
【发布时间】:2023-03-22 11:50:01
【问题描述】:

我使用了 UICollectionView,并使用 API 的结果填充它。 API中有ID、图像、名称、描述和喜欢的真假。 我已经实现了所有这些东西,现在所有结果都加载到了这个集合视图中。

    extension VCResCourses : UICollectionViewDelegate {

}

extension VCResCourses: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
    {
        let length = (UIScreen.main.bounds.width - 16)
        return CGSize(width: length, height: 135);
    }
}

extension VCResCourses : UICollectionViewDataSource {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

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

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let currentCell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier,for:indexPath) as! CVCResCourse

    let doCourses: [DOCourses] = dataSources.total()
    let doCourse = doCourses[indexPath.row]

    let courseId = doCourse.Id!
    var courseName = doCourse.Name!
    let courseAddress = doCourse.Address!
    let courseImage = doCourse.Image!
    let courseWish = doCourse.Wish!

    courseName = courseName.replacingOccurrences(of: "\t", with: "", options: .literal, range: nil)

    currentCell.imageView.kf.setImage(with: URL(string: courseImage))
    currentCell.textPrimary.text = courseName.capitalized
    currentCell.textSecondary.text = courseAddress.capitalized
    currentCell.buttonOpen.addTarget(...)
    currentCell.buttonFav.addTarget(...)

    return currentCell
    }
}

我现在正在尝试的是每个 CELL 上有两个按钮,一个打开记录的详细信息,另一个设置收藏夹为真或假。

现在我需要获取当前记录的 id 并将其收藏状态切换为 true 或 false 或使用 id 打开详细信息页面。我无法为按钮添加操作并使用 ID 执行收藏或打开详细信息操作。

在 android 中,我通过在 CustomBaseAdapter 中添加 clickListener 来完成此操作,它为数据的每一行或记录执行操作。我也需要在 iOS 中做同样的事情,但还没有运气

我是iOS开发新手,请帮忙

【问题讨论】:

    标签: ios swift3 uicollectionview uicollectionviewcell


    【解决方案1】:

    您需要为 e,g 的每个按钮设置 tag

    currentCell.buttonOpen.tag = indexPath.row
    currentCell.buttonFav.tag = indexPath.row
    currentCell.buttonOpen.addTarget(self, action: #selector(self.buttonClicked), for: .touchUpInside)
    

    您可以通过 button.tag 获取 id,例如

    func buttonClicked(_ sender: UIButton) {
      let doCourses: [DOCourses] = dataSources.total()
      let doCourse = doCourses[sender.tag]
     let courseId = doCourse.Id!
      print (courseId)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-15
      • 2017-01-20
      • 1970-01-01
      • 2012-11-08
      相关资源
      最近更新 更多