Swift 在UICollectionView中选择单个UILabel

Swift 在UICollectionView中选择单个UILabel,swift,uicollectionview,uilabel,uicollectionviewcell,Swift,Uicollectionview,Uilabel,Uicollectionviewcell,我创建了一个水平UICollectionView,它显示12个月,我需要用户选择其中一个月,为此,我使用了collectionCell.isUserInteractionEnabled=true和UITapGestureRecognitor,但这会返回整个页面中的月份 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewC

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

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")
输出:

八月

九月

十月

十一月

十二月

四月

玷污

二月

一月


你真的应该使用collectionView的委托方法,
didSelectItemAt()
,而不是使用手势识别器。

在探索过程中,我发现我们可以使用

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)
  }

将UICapgestureRecognitor与UICollectionView一起使用就像将任何手势识别器与UITableView一起使用一样。这是一个很滑的斜坡。你为什么不使用didSelectRowAt?你为什么用手势?