简体   繁体   English

如何从行索引Swift获取indexpath

[英]How to get indexpath from row index Swift

I am loading an array to UIcollectionview (later will add other data) . 我正在向UIcollectionview加载一个数组(稍后将添加其他数据)。 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? 无法将Int类型的值转换为预期的参数类型'IndexPath?

I can understand this exception as indexpath is different in swift from collection data index(array index). 我可以理解这个异常,因为indexpath在swift中与集合数据索引(数组索引)不同。 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. 我是iOS的新手,所以可能不擅长为这样的问题搜索正确的关键字。 It will be a great favour from you all for any other method to this requirement. 对于满足此要求的任何其他方法,对您来说都是一个很大的帮助。

IndexPath 3中为UICollectionView创建UICollectionView

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

你可以使用它

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

Swift 3最新消息

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

Swift 4.1. Swift 4.1。 Here I created function to get NSIndexPath. 在这里我创建了获取NSIndexPath的函数。 Just pass your UIView(UIButton,UITextField etc) and UICollectionView object to get NSIndexPath. 只需传递你的UIView(UIButton,UITextField等)和UICollectionView对象来获取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?
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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