Reputation: 343
I have created XIB with UIView
. I have assigned class MyViewControl: UIControl
to it, so I can add touch up inside action. It works, touches are called inside my class.
Now, I have created UICollectionView
and add this "xib" as cell view. I want now touches to be handled inside UICollectionViewDelegate
class. So I have done this:
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
for v in cell.contentView.subviews {
if let c: MyViewControl = v as? MyViewControl {
c.isUserInteractionEnabled = true
c.addTarget(self, action: #selector(myClick), for: UIControlEvents.touchUpInside)
}
}
}
func myClick(sender: Any){
print("click....")
}
However, myClick
selector is never called. If I add UIButton
to the MyViewControl
and do the same thing (addTarget
) for this button, callbacks are correctly called.
Upvotes: 2
Views: 4519
Reputation: 50
Add underscore _
before sender in function as _ sender: Any
and add (_:)
in the #selector
under action
viz. myClick(_ :)
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
for v in cell.contentView.subviews {
if let c: MyViewControl = v as? MyViewControl {
c.isUserInteractionEnabled = true
c.addTarget(self, action: #selector(myClick(_:)), for: UIControlEvents.touchUpInside)
}
}
}
func myClick(_ sender: Any){
print("click....")
}
Hope this helps
Upvotes: 2