Why UICollectionView didSelect method does not work?

廉价感情. 提交于 2019-12-22 07:58:17

问题


I've created my UICollectionView programmatically and in this case my didSelectItemAtIndexPath method does not call at all.

let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: CGRectGetWidth(self.view.frame), height: 360), collectionViewLayout: layout)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.userInteractionEnabled = true

So, what is a problem? Why when I tap on the cells I do not get my response?

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    print("Selected Cell: \(indexPath.row)")
}

回答1:


i Know this may be late, but for the sakes of feature purpose, CollectionView[didSelectItem] not responding to touch could be as a result of you also enalbing addGestureRecognizer so check if you have set a gesture recognizer on your CollectionView like so collectionView?.addGestureRecognizer(tapGestRecognizer)




回答2:


Select ViewController.swift in Project Navigator. Update the class declaration with this:

class ViewController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource 


//After class declaration create a new variable:

 var collectionView: UICollectionView!



  override func viewDidLoad() {
   super.viewDidLoad()
     // Do any additional setup after loading the view, typically from a nib.
   let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
   layout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
   layout.itemSize = CGSize(width: 90, height: 120)

   collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
   collectionView.dataSource = self
   collectionView.delegate = self
   collectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
   collectionView.backgroundColor = UIColor.whiteColor()
   self.view.addSubview(collectionView)
}



func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    print("Selected Cell: \(indexPath.row)")
}



回答3:


check in UiCollectionviewCell subclass isUserInteractionEnabled property or set it programaticaly to true

self.contentView.isUserInteractionEnabled = true


来源:https://stackoverflow.com/questions/39036197/why-uicollectionview-didselect-method-does-not-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!