【问题标题】:Opening another viewcontroller when clicking on cell of collectionview单击collectionview的单元格时打开另一个视图控制器
【发布时间】:2021-09-11 03:23:34
【问题描述】:

我是 swift 新手,我按照这个视频做了一个收藏视图,它运行良好。但是在单击时从一个单元格单击到另一个单元格不起作用。

https://www.youtube.com/watch?v=TQOhsyWUhwg

func collectionView(_ collectionView: UICollectionView, 
  didSelectItemAt indexPath: IndexPath) {
    print("Cell \(indexPath.row + 1) clicked")
  }

这里打印被选中的单元格。单击单元格时,我只需要打开另一个视图。谁能帮帮我。

【问题讨论】:

  • "单击单元格时我只需要打开另一个视图" 打开另一个视图是什么意思?转换到不同的视图控制器?
  • 是的另一个视图控制器..对不起
  • 通过运行搜索来帮助自己。有很多类似的话题等着你。

标签: swift xcode uicollectionview uicollectionviewcell collectionview


【解决方案1】:

您只需要创建另一个视图控制器的对象并推送它。 喜欢:

let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "your_view_identifier") as! Your_ViewController
self.navigationController?.pushViewController(nextViewController, animated: true)

【讨论】:

    【解决方案2】:

    让我们猜测您要导航的 viewController 是SecondViewController。故事板名称是Main

    导航 ViewController

    1. 您需要创建该 ViewController 的实例
    2. 您需要从 Navigation Controller 推送该 viewController
    class SecondViewController: UIViewController {
        
    }
    
    var secondViewController: SecondViewController {
        let st = UIStoryboard(name: "Main", bundle: nil)
        let vc = st.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController
        return vc
    }
    

    现在,如果您想通过单元格点击导航视图控制器。只需将该视图控制器推入您的导航堆栈即可。

    func collectionView(_ collectionView: UICollectionView, 
      didSelectItemAt indexPath: IndexPath) {
        print("Cell \(indexPath.row + 1) clicked")
        self.navigationController?.pushViewController(secondViewController, animated: true)
      }
    

    【讨论】:

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