繁体   English   中英

如何从行索引Swift获取indexpath

[英]How to get indexpath from row index Swift

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

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

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

这是在大胆的位置给我错误说:

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

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

我是iOS的新手,所以可能不擅长为这样的问题搜索正确的关键字。 对于满足此要求的任何其他方法,对您来说都是一个很大的帮助。

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。 在这里我创建了获取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