当我在一个单元格上按一个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
    }

最佳答案

使用**indexPathsForSelectedItems**UICollectionView属性获取所有indexPaths selectedUICollectionViewCells。您获得的元素数量取决于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上调用button tap并在prepare(for segue: UIStoryboardSegue, sender: Any?)中完成其余工作

关于swift - 集合 View 外部有一个按钮可以执行集合 View 单元格应该执行的操作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45682835/

10-14 23:45
查看更多