How to get indexpath from row index Swift

十年热恋 提交于 2019-12-06 03:02:36

问题


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.


回答1:


To create an IndexPath in swift 3 for UICollectionView

let indexPath = IndexPath(item: 0, section: 0)



回答2:


You can use it

let indexPath = NSIndexPath(forRow: 0, inSection: 0)



回答3:


Swift 3 Latest

self.table.reloadRows(at: [IndexPath(row: 0, section: 0)], with: .fade)



回答4:


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?
    }


来源:https://stackoverflow.com/questions/41695210/how-to-get-indexpath-from-row-index-swift

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