SKY*_*ine 3 collectionview uistoryboardsegue swift
我没有找到任何好的例子来使用swift做我想做的事情所以我允许自己提出这个问题.
我使用collectionView来显示PFObjects,我想使用prepareForSegue将显示的单元格数据发送到第二个控制器.
在这一点上,我努力使这部分代码工作:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == "goto_answerquestion"){
var indexpath : NSIndexPath = self.collectionView.indexPathsForSelectedItems()
}
}
Run Code Online (Sandbox Code Playgroud)
这一行:
var indexpath : NSIndexPath = self.collectionView.indexPathsForSelectedItems()
Run Code Online (Sandbox Code Playgroud)
触发以下错误:
(UICollectionView, numberOfItemsInSection: Int)-> Int does not have a member named 'indexPathsForSelectedItems'
Run Code Online (Sandbox Code Playgroud)
如果我使用了错误的方法,或者如果您需要其他数据来对问题进行适当的概述,请告诉我.
回答
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == "segue_identifier"){
// check for / catch all visible cell(s)
for item in self.collectionView!.visibleCells() as [UICollectionViewCell] {
var indexpath : NSIndexPath = self.collectionView.indexPathForCell(item as CollectionViewCell)!
var cell : CollectionViewCell = self.collectionView!.cellForItemAtIndexPath(indexpath) as CollectionViewCell
// Grab related PFObject
var objectData:PFObject = self.questionData.objectAtIndex(indexpath.row) as PFObject
// Pass PFObject to second ViewController
let theDestination = (segue.destinationViewController as answerPageViewController)
theDestination.questionObject = objectData
}
}
}
Run Code Online (Sandbox Code Playgroud)
BJ *_*ler 10
如果您只是想找到被轻击的单元格的索引路径,而不是多个,则可以在prepareForSegue方法中执行此操作:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let indexPath = collectionView.indexPathForCell(sender as UICollectionViewCell)
// do what you need now with the indexPath
}
Run Code Online (Sandbox Code Playgroud)
sender 在这种情况下,您使用的是单元格,因此您只需将其强制转换为UICollectionViewCell(或自定义单元格子类,如果您创建了一个).
更新:
Swift 1.2引入as!替换as为此目的,所以为了保持安全,你可以尝试prepareForSegue使用多个绑定内部:
if let cell = sender as? UICollectionViewCell, indexPath = collectionView.indexPathForCell(cell) {
// use indexPath
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10390 次 |
| 最近记录: |