Jeffrey Neo
Jeffrey Neo

Reputation: 3809

Why is viewDidLoad run before didSelectItemAtIndexPath?

I am using UICollectionViewDataSource & UICollectionViewDelegate in my personal ViewController subclass file. I can now click on the cell in CollectionView and navigate to the child ViewController I want, but the target's viewDidLoad method is always run before the didSelectItemAtIndexPath, so I can't get the selected cell's info before the view comes out, for example to get the label name of the selected cell.

Below is the codes I did for now, line 2 is always comes before line 1, but I need to get line 1 first, any ideas?

in UICollectionView's ViewController with datasource and delegate:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    println("1")  //line 1
}

in target's ViewController:

override func viewDidLoad() {
    super.viewDidLoad()

    println("2")  //line 2
}

P.S: push segue is using from main to target.

Upvotes: 1

Views: 126

Answers (2)

Jeffrey Neo
Jeffrey Neo

Reputation: 3809

Use didHighlightItemAtIndexPath instead of didSelectItemAtIndexPath solved my problem.

Upvotes: 1

rob mayoff
rob mayoff

Reputation: 385930

Use prepareForSender:segue: instead of collectionView:didSelectItemAtIndexPath:. The sender is the cell that was tapped. If you need its index path, you can get it from the collection view using indexPathForCell: (passing the sender as the argument).

Upvotes: 0

Related Questions