【问题标题】:have a button outside the collection view to do what the collection view cell is supposed to do在集合视图之外有一个按钮来执行集合视图单元应该执行的操作
【发布时间】:2017-08-14 20:49:57
【问题描述】:

当我按下单元格时,我有一个作为图像轮播的集合视图,一个 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
    }

【问题讨论】:

  • 您希望对按钮按下而不是在单元格选择上进行操作?
  • 是的,但我希望按钮位于集合视图和集合视图单元格之外。有可能吗?
  • 如何同时选择单元格和按钮?
  • 这是一个图像轮播,我不想选择单元格我想选择一个按钮,但我不知道如何访问 indexPath 我必须在按钮函数 self.selectedIndexPath = indexPath 中使用这一行/跨度>
  • 您想在点击按钮时访问哪个索引路径?

标签: swift uicollectionview nsindexpath


【解决方案1】:

使用UICollectionView**indexPathsForSelectedItems** 属性获取所有selected UICollectionViewCells 中的indexPaths。您获得的元素数量取决于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 来跟踪所选单元格。只需在button tap 上致电performSegue,然后在prepare(for segue: UIStoryboardSegue, sender: Any?) 中完成其余工作

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多