【问题标题】:Selecting a single UILabel in a UICollectionView在 UICollectionView 中选择单个 UILabel
【发布时间】:2018-06-23 13:14:49
【问题描述】:

我创建了一个显示 12 个月的水平 UICollectionView,我需要用户选择其中一个,为此我使用了 collectionCell.isUserInteractionEnabled=trueUITapGestureRecognizer,但这会返回整个页面中的月份。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let collectionCell = collectionView.dequeueReusableCell(withReuseIdentifier: "monthCollectionView", for: indexPath as IndexPath) as! AttendenceCollectionViewCell
    collectionCell.collectionViewCellLabel.text=monthArray[indexPath.item]
    collectionCell.backgroundColor = UIColor.clear
    collectionCell.isUserInteractionEnabled=true
    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(customMonth(month:tap:)))
    collectionCell.collectionViewCellLabel.addGestureRecognizer(tapGesture)
    collectionCell.collectionViewCellLabel.isEnabled=true
    collectionCell.isExclusiveTouch=true

    customMonth(month:monthArray[indexPath.item],tap: tapGesture)


    return collectionCell
}


@objc func customMonth(month:String,tap:UITapGestureRecognizer){
    print("\n",month,"\n")

输出:

八月

九月

十月

十一月

十二月

四月

三月

二月

一月

【问题讨论】:

  • 在 UICollectionView 中使用 UITapGestureRecognizer 就像在 UITableView 中使用任何手势识别器一样。这是一个滑坡。
  • 为什么不使用 didSelectRowAt?为什么要使用 tapGesture?

标签: swift uicollectionview uilabel uicollectionviewcell


【解决方案1】:

您确实应该使用 collectionView 的委托方法 didSelectItemAt() 而不是使用手势识别器。

【讨论】:

    【解决方案2】:

    在探索时我发现我们可以使用

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
    

    用于在 UICollectionView 中选择项目

    它是这样实现的:

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let selectedMonth=monthArray[indexPath.item]
        collectionView.cellForItem(at: indexPath)
        print("\n\n",selectedMonth)
      }
    

    【讨论】:

      猜你喜欢
      • 2020-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多