Как получить выбранный элемент в представлении коллекции с помощью indexPathsForSelectedItems
у меня есть collectionView фотографий и хочу передать фотографию, которая была клик в detailViewControler.
данные по собрания приходят от:
 var timeLineData:NSMutableArray = NSMutableArray ()
Я хотел бы использовать метод prepare for 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
    }
} 
4 ответов
аргумент отправителя в prepareForSegue: sender: будет ячейкой, если вы подключили сегмент из ячейки. В этом случае вы можете получить 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
    }
} 
на indexPathsForSelectedItems возвращает массив indexPaths (так как может быть выбрано несколько элементов), поэтому вам нужно использовать:
let indexPaths : NSArray = self.collectionView!.indexPathsForSelectedItems()
let indexPath : NSIndexPath = indexPaths[0] as NSIndexPath
(вероятно, вы должны проверить, выбраны ли несколько элементов, и соответственно обработать).
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
        }
    }
}
