我有一个照片集合视图,想要将照片传递给一个detailViewControler。
收集数据来自:
var timeLineData:NSMutableArray = NSMutableArray ()
我想使用准备segue方法。
我的问题是如何从单击的单元格中获取好的indexPath?
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue == "goToZoom" {
let zoomVC : PhotoZoomViewController = segue.destinationViewController as PhotoZoomViewController
let cell = sender as UserPostsCell
let indexPath = self.collectionView!.indexPathForCell(cell)
let userPost = self.timeLineData.objectAtIndex(indexPath!.row) as PFObject
zoomVC.post = userPost
}
}
答案 0 :(得分:32)
prepareForSegue:sender:中的sender参数将是从单元格连接segue的单元格。在这种情况下,您可以从单元格中获取indexPath,
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showZoomController" {
let zoomVC = segue.destinationViewController as PhotoZoomViewController
let cell = sender as UICollectionViewCell
let indexPath = self.collectionView!.indexPathForCell(cell)
let userPost = self.timeLineData.objectAtIndex(indexPath.row) as PFObject
zoomVC.post = userPost
}
}
答案 1 :(得分:16)
indexPathsForSelectedItems
返回一个indexPaths数组(因为可能选择了几个项目)所以你需要使用:
let indexPaths : NSArray = self.collectionView!.indexPathsForSelectedItems()
let indexPath : NSIndexPath = indexPaths[0] as NSIndexPath
(您可能应该测试是否选择了多个项目,并相应处理)。
答案 2 :(得分:4)
在swift 3中:
let index = self.collectionView.indexPathsForSelectedItems?.first
答案 3 :(得分:2)
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == “segueID”{
if let destination = segue.destination as? YourDestinationViewController{
let cell = sender as! UICollectionViewCell
let indexPath = myCollectionView.indexPath(for: cell)
let selectedData = myArray[(indexPath?.row)!]
// postedData is the variable that will be sent, make sure to declare it in YourDestinationViewController
destination.postedData = selectedData
}
}
}
答案 4 :(得分:-1)
Objective-c :
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
PhotoZoomViewController *zoomVC = [segue destinationViewController];
NSIndexPath *path = [self.collectionView indexPathForCell:(sender)];
NSDictionary *dataObj = [timeLineData objectAtIndex:path.row];
// In PhotoZoomViewController create NSDictionary with name myDictionary
// in this line will copy the dataObj to myDictionary
zoomVC.myDictionary = dataObj;
}
快速:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let zoomVC = segue.destinationViewController as PhotoZoomViewController
let cell = sender as UICollectionViewCell
let indexPath = self.collectionView!.indexPathForCell(cell)
let userPost = self.timeLineData.objectAtIndex(indexPath.row) as PFObject
zoomVC.post = userPost
}