如何从不同的集合视图单元到不同的视图控制器
Posted
技术标签:
【中文标题】如何从不同的集合视图单元到不同的视图控制器【英文标题】:How to Segue from different Collection View Cells to different View Controllers 【发布时间】:2019-10-19 18:31:22 【问题描述】:这里是初学者。我正在开发一个简单的灯具应用程序。我已经设置了一个集合视图,我正在尝试这样做,所以当我单击集合视图中的一个单元格时,它会将我带到相应的视图控制器。每个单元格都应该连接到不同的视图控制器。这是我到目前为止尝试过的代码:
import UIKit
class FixturesViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout
let fixturesName = ["EUMHC 1's XI", "EUMHC 2's XI", "EUMHC 3's XI", "EUMHC 4's XI", "EUMHC 5's XI", "EUMHC 6's XI", "EUMHC 7's XI"]
let fixturesLeague = ["Competing in Men's Premiership & Premier North (BUCS)", "Competing in Men's Regional Division 1 & Scottish 1 (BUCS)", "Competing in Men's Regional Division 2 & Scottish 2 (BUCS)", "Competing in Men's East District Division 1 & Scottish 3 (BUCS)", "Competing in Men's East District Division 2 & Scottish 3 (BUCS)", "Competing in Men's East District Division 2 & Scottish 4 (BUCS)", "Competing in Men's East District Division 4"]
override func viewDidLoad()
super.viewDidLoad()
// Do any additional setup after loading the view.
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
return fixturesName.count
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell2", for: indexPath) as! FixturesCollectionViewCell
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
cell.fixturesName.text = fixturesName[indexPath.row]
cell.fixturesLeague.text = fixturesLeague[indexPath.row]
cell.contentView.layer.cornerRadius = 10.0
cell.layer.cornerRadius = 10.0
cell.contentView.layer.borderWidth = 1.0
cell.contentView.layer.borderColor = UIColor.clear.cgColor
cell.contentView.layer.masksToBounds = true
cell.layer.shadowColor = UIColor.gray.cgColor
cell.layer.shadowOffset = CGSize(width: 0, height: 1.0)
cell.layer.shadowRadius = 4.0
cell.layer.masksToBounds = false
cell.layer.shadowOpacity = 1.0
return cell
private func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
switch (indexPath.row)
case 0:
self.performSegue(withIdentifier: "fixtures1", sender: self)
case 1:
self.performSegue(withIdentifier: "fixtures2", sender: self)
default:
break
我尝试在底部使用 switch 语句(在别处看到此方法)根据单元格的索引执行带有标识符的 segues。
这是处理它的正确方法吗?
【问题讨论】:
【参考方案1】:如果你有很多segue,那么最好这样构建
self.performSegue(withIdentifier: "fixtures\(indexPath.item + 1)", sender: self)
segues 从 fixtures1
开始到 fixturesN
【讨论】:
非常感谢!我应该在哪里将它嵌入到我的代码中以使其正常工作。对不起,初学者的问题 在didSelectItemAtIndexPath
内
好的,这就是我所做的,但单元格仍然不可点击,是不是我缺少一些东西才能使它们如此?如果它很重要,我从情节提要中定义了 segues,并给它们提供了标识符 fixtures1 到 fixturesn
非常感谢,我只需要更改我原始代码的一些部分才能让它工作,现在完全欣喜若狂地被困在这个问题上好多年了。再次干杯!以上是关于如何从不同的集合视图单元到不同的视图控制器的主要内容,如果未能解决你的问题,请参考以下文章
如何在swift中基于Json id从集合视图didSelectItemAt推送不同的视图控制器