[英]Why is the didSelectItemAtIndexPath not getting called?
I have a UILabel in collection view cell and when I select it I want the background of the label to change color, but nothing happens when I click a cell? 我在集合视图单元格中有一个UILabel,当我选择它时,我希望标签的背景更改颜色,但是单击单元格时什么都没发生? Why is that and how do I fix it?
为什么会这样,我该如何解决? nothing is getting printed in the console.
控制台中没有任何内容。
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
}
}
I think you are tapping on label to change the color of label. 我认为您正在点击标签以更改标签的颜色。
didSelectitemAtIndexpath
will not called if you tap the label. 如果点击标签,则不会调用
didSelectitemAtIndexpath
。 For that you need to add UITapGestureRecognizer to your label. 为此,您需要将UITapGestureRecognizer添加到标签。
In your cellForRow try setting label.tag = indexPath.row
and then add tapGesture
to the label. 在您的cellForRow中,尝试设置
label.tag = indexPath.row
,然后将tapGesture
添加到标签中。 And in the target of it change the color of label. 并在其目标中更改标签的颜色。 And don't forget to set
userInteractionEnable = true
as label
property. 并且不要忘记将
userInteractionEnable = true
设置为label
属性。
EDIT 编辑
@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()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.