Как получить выбранный элемент в представлении коллекции с помощью indexPathsForSelectedItems

У меня есть коллекцияView фотографий и хочу передать фотографию, которая была привязана к 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

    }
} 

Ответ 1

Аргумент отправителя в файле prepareForSegue: 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
    }
} 

Ответ 2

indexPathsForSelectedItems возвращает массив indexPaths (так как может быть выбран несколько элементов), поэтому вам нужно использовать:

let indexPaths : NSArray = self.collectionView!.indexPathsForSelectedItems()
let indexPath : NSIndexPath = indexPaths[0] as NSIndexPath

(Вероятно, вам нужно проверить, выбрано ли несколько элементов и соответственно обрабатывать).

Ответ 3

В быстром 3:

let index = self.collectionView.indexPathsForSelectedItems?.first

Ответ 4

Swift 3.0

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
        }
    }
}

Ответ 5

Цель-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;

}