7

I am loading an array to UIcollectionview(later will add other data) . I want to select collection view item randomly as:

var indexpath = Int(arc4random_uniform(UInt32(items.count)-1) 

self.collectionview.selectitem(at: **indexpath**, animated:true ,scrollPosition:UICollectionViewScrollPosition)

Here it’s giving me error at bold position saying:

cannot convert value of type Int to expected argument type 'IndexPath?

I can understand this exception as indexpath is different in swift from collection data index(array index). But I am unable to find any method that can convert item index to indexpath or anyother way.

I am newer to iOS so might be not good at searching correct keywords for such issue. It will be a great favour from you all for any other method to this requirement.

bfontaine
  • 18,169
  • 13
  • 73
  • 107
Saira Nawaz
  • 710
  • 2
  • 10
  • 24

4 Answers4

34

To create an IndexPath in swift 3 for UICollectionView

let indexPath = IndexPath(item: 0, section: 0)
KrishnaCA
  • 5,615
  • 1
  • 21
  • 31
3

You can use it

let indexPath = NSIndexPath(forRow: 0, inSection: 0)
Syed Ali Salman
  • 2,894
  • 4
  • 33
  • 48
1

Swift 3 Latest

self.table.reloadRows(at: [IndexPath(row: 0, section: 0)], with: .fade)
Uma Madhavi
  • 4,851
  • 5
  • 38
  • 73
Urvish Modi
  • 1,118
  • 10
  • 11
0

Swift 4.1. Here I created function to get NSIndexPath. Just pass your UIView(UIButton,UITextField etc) and UICollectionView object to get NSIndexPath.

func getIndexPathFor(view: UIView, collectionView: UICollectionView) -> NSIndexPath? {

        let point = collectionView.convert(view.bounds.origin, from: view)
        let indexPath = collectionView.indexPathForItem(at: point)
        return indexPath as NSIndexPath?
    }
Gurjinder Singh
  • 9,221
  • 1
  • 66
  • 58