简体   繁体   中英

Why is my UICollectionView cell not clickable in my swift ios app?

I'm using UICollectionView in my swift class, it's placed on my UIViewController . I connected the collectionView to the outlet in my code, I set up delegate and datasource and I see the outcome in my app. Everything works besides the fact that when I click each cell - nothing happens.

My code is as follows:

class UsersList: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {


@IBOutlet weak var tview: UICollectionView!

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    tview.backgroundColor = UIColor.whiteColor() //this works
    tview.delegate = self
    tview.dataSource = self
}

func collectionView(tview: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    print("You selected cell #\(indexPath.item)!")
    //this does not appear in the console :(
}

Is there anything else I could do to see the print msg in the console?

In swift, the parameter name and function name identify a function together. UICollectionViewDelegate have function

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)

but not

func collectionView(tview: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)

Try removing all of your UIGestures from the view then test to see if the UICollectionView Cells are able to be interacted with normally.

In my case, I had to remove the lines:

let tap = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
    self.view.addGestureRecognizer(tap)

For some reason this was getting in the way of being able to click on my cells.

For me, I had to set the UICollectionView 's delegate. For example, in viewDidLoad() :

collectionView.delegate = self

This is necessary or the delegate methods will not be called!

请确保在故事板中启用了用户交互

我不得不在情节提要中将滚动方向从垂直更改为水平,这对我有用。

My problem was that isUserInteractionEnabled was false for the parent view of the collectionView. I had taken the code for the parent view from somewhere else where evidently that had been the right thing to do. But not here... Sigh...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM