为什么不调用didSelectItemAtIndexPath?

时间:2016-02-16 03:42:00

标签: ios swift uitableview

我在集合视图单元格中有一个UILabel,当我选择它时,我希望标签的背景改变颜色,但是当我点击一个单元格时没有任何反应?为什么这样,我该如何解决?没有任何东西在控制台中打印出来。

class newview: UIViewController,UICollectionViewDataSource, UICollectionViewDelegate{
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    print("called")
    var cell: customcell = timecollection.cellForItemAtIndexPath(indexPath) as! customcell

    cell.clabel.tag = indexPath.item
    let tapGesture = UITapGestureRecognizer(target: self, action: "choose:")
    cell.clabel.addGestureRecognizer(tapGesture)
    cell.clabel.userInteractionEnabled = true

    cell.clabel.textColor = UIColor.whiteColor()
    cell.clabel.layer.borderWidth = 0.5
    cell.clabel.layer.borderColor = UIColor.whiteColor.CGColor

     }

func choose(gest: UITapGestureRecognizer){
     let label: UILabel = gest.view as! UILabel
    label.backgroundColor = UIColor.whiteColor
     }  
}

1 个答案:

答案 0 :(得分:1)

我认为你正在点击标签来改变标签的颜色。如果点击标签,则不会调用didSelectitemAtIndexpath。为此,您需要将UITapGestureRecognizer添加到标签中。

在您的cellForRow中尝试设置label.tag = indexPath.row,然后将tapGesture添加到标签中。并且在它的目标中改变标签的颜色。并且不要忘记将userInteractionEnable = true设置为label属性。

修改

 @IBAction func btnTapped(gest: UITapGestureRecognizer) {
        print("Called")
      let label:UILabel = (gest.view as! UILabel) // Type cast it with the class for which you have added gesture
      label.backgroundColor = UIColor.redColor()
  }