7

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

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

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

在这里,它在粗体位置给了我错误说:

无法将 Int 类型的值转换为预期的参数类型“IndexPath?

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

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

4

4 回答 4

33

IndexPath在 swift 3 中创建一个UICollectionView

let indexPath = IndexPath(item: 0, section: 0)
于 2017-01-17T11:23:35.213 回答
3

你可以使用它

let indexPath = NSIndexPath(forRow: 0, inSection: 0)
于 2017-01-17T10:54:05.377 回答
1

斯威夫特 3 最新

self.table.reloadRows(at: [IndexPath(row: 0, section: 0)], with: .fade)
于 2017-06-29T10:53:15.617 回答
0

斯威夫特 4.1。在这里,我创建了获取 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?
    }
于 2018-06-20T14:51:31.710 回答