ios 如何从行索引 Swift 获取索引路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41695210/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 11:03:57  来源:igfitidea点击:

How to get indexpath from row index Swift

iosswiftcollectionviewindexpath

提问by Saira Nawaz

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

我正在加载一个数组UIcollectionview(稍后将添加其他数据)。我想随机选择集合视图项目:

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 indexpathis 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.

我可以理解此异常与indexpathswift 中的集合数据索引(数组索引)不同。但是我找不到任何可以将项目索引转换为 indexpath 或任何其他方式的方法。

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.

我是 iOS 新手,所以可能不擅长为此类问题搜索正确的关键字。对于满足此要求的任何其他方法,这将是你们所有人的一大福音。

回答by KrishnaCA

To create an IndexPathin swift 3 for UICollectionView

创建一个IndexPathin swift 3 forUICollectionView

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

回答by Syed Ali Salman

You can use it

你可以使用它

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

回答by Urvish Modi

Swift 3 Latest

斯威夫特 3 最新

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

回答by Gurjinder Singh

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

斯威夫特 4.1。在这里我创建了函数来获取 NSIndexPath。只需传递您的 UIView(UIButton,UITextField etc) 和 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?
    }