在集合视图外部有一个按钮来执行集合视图单元应该执行的操作

时间:2017-08-14 20:49:58

标签: swift uicollectionview nsindexpath

当我按下单元格时,我有一个集合视图作为图像轮播,pdf文件将打开,下面的代码将执行此操作。我想做的是按一下按钮而不是按下电池本身。但由于该行self.selectedIndexPath = indexPath

,我不知道该怎么做
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        self.selectedIndexPath = indexPath
        self.performSegue(withIdentifier: "showBook", sender: self)
    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?)
    {
        if segue.identifier == "showBook"
        {
            let vc = segue.destination as! showMo2lfatVC
            vc.book = self.arrayBooks[self.selectedIndexPath.row]    
        }
    }

这是我的按钮功能,这是我试过的

@IBAction func openBook(_ sender: Any) {

     //   self.selectedIndexPath = indexPath
       // self.performSegue(withIdentifier: "showImage", sender: self)
     //    self.selectedIndexPath = indexPath
    }

1 个答案:

答案 0 :(得分:0)

使用**indexPathsForSelectedItems**的{​​{1}}属性获取所有UICollectionView indexPaths的{​​{1}}。您获得的元素数量取决于selected是否允许UICollectionViewCells

示例:

multiple selection

无需创建任何单独的变量UICollectionView来保持所选单元格的轨道。只需在override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showBook" { let vc = segue.destination as! ViewController2 if let selectedIndexPath = self.collectionView.indexPathsForSelectedItems?.first //Here { vc.book = self.arrayBooks[selectedIndexPath.row] } } } @IBAction func openBook(_ sender: UIButton) { self.performSegue(withIdentifier: "showBook", sender: self) } 上致电selectedIndexPath,然后在performSegue

中完成剩下的工作