我创建了一个水平 UICollectionView,它显示 12 个月,我需要用户选择其中之一,为此我使用了 collectionCell.isUserInteractionEnabled=true
和 UITapGestureRecognizer
但这会返回整个页面中的月份。
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")
输出:
Aug
Sep
Oct
Nov
Dec
Apr
Mar
Feb
Jan
最佳答案
您确实应该使用 collectionView 的委托(delegate)方法 didSelectItemAt()
而不是使用手势识别器。
关于swift - 在 UICollectionView 中选择单个 UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51001517/