首页 > 解决方案 > 单击 collectionView 转到另一个具有不同数组的 collectionView

问题描述

我对 swift 还很陌生,有一个问题我想问。

我有三个 ViewController,前两个有集合视图,最后一个没有。

我有它,以便第一个控制器在集合视图中显示两个数组。第一个是字符串数组,第二个是图像数组,这是为了让它们在集合视图上正确排列。

这是我很难理解的。当单击集合视图单元格时,我如何让它转到第二个控制器(那里有另一个集合视图)并显示一个完全不同的数组。我希望它每次单击第一个控制器的每个单元格都会显示一个不同但特定的数组。

单击第二个视图控制器集合单元格后,它将转到带有图像、标签和文本视图的视图控制器,本质上我需要为每个单击的单元格显示一组不同的数据。

我真的不知道从哪里开始,我相信这可能与字典有关,但我不知道从哪里开始。

他是我用于第一个具有集合视图的视图控制器的代码


class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {


    @IBOutlet weak var collectionView: UICollectionView!


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        collectionView.delegate = self
        collectionView.dataSource = self

    }


    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize{
          return CGSize(width: 160.0, height: 210.0)
       }


    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return labelArray.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell

        cell.imageView.image = imageArray[indexPath.item]
        cell.label.text = labelArray[indexPath.item]

        return cell
    }

}

我只是不知道从哪里开始,任何帮助将不胜感激!谢谢![在此处输入图像描述] 1

标签: arraysswiftxcode

解决方案


您需要实施func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath). 请参阅Apple 文档

在其中,您可以调用 segue,它导航到下一个控制器,例如:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    // Get selected row, you can then do something for each row
    let selectedRow = indexPath.row // can also get indexPath.section or .item
    self.performSegue(withIdentifier: "your identifier", sender: self)
}

如果你想将一些数据从第一个控制器传递到下一个控制器,你可以传递一个数据override func prepareForSegue(segue: UIStoryBoardSegue, sender: AnyObject?)

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "your identifier" {
        var dest = segue.destinationViewController as! YourViewControllerType
        dest.anotherArray = ["whatever", "you", "want"]
}

当然假设YourViewControllerType会有一个成员var anotherArray: [String]?(当然可以更改类型和名称)。

一个更好的方法是定义一个合适的模型类来保存目标控制器的数据。


推荐阅读