swift - 从 Collection View 执行segue

标签 swift collections view segue

我的目标是执行从 Collection View 单元到 View Controller 的segue。在下一个 View Controller 中我有声明

 let selectedCar = CarViewController()

 if selectedCar.selectedMaker == "a"

我知道如何使用附加类执行segue,但不知道如何使用 Collection View 执行。我将indexPath 与if else 语句一起使用。 Segue 名称是“toModels”

class CarsViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {

public var selectedMaker = ""

@IBOutlet weak var collectionView: UICollectionView!

let mainMenu = ["a","b"]

override func viewDidLoad() {
    super.viewDidLoad()

    collectionView.delegate = self
    collectionView.dataSource = self
}

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

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

    cell.imageCell.image = UIImage(named: mainMenu[indexPath.row])
    cell.labelCell.text = mainMenu[indexPath.row].capitalized

    return cell
}

public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    performSegue(withIdentifier: "toModels", sender: selectedMaker)

    if indexPath == [0, 0]
    {
        selectedMaker = "a"
        print("a")
    }
    else if indexPath == [0, 1]
    {
        selectedMaker = "b"
        print("b")
    }

最佳答案

试试这个编辑

public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    if indexPath.item == 0
    {
        selectedMaker = "a"
        print("a")
    }
    else if indexPath.item == 1
    {
        selectedMaker = "b"
        print("b")
    }
    performSegue(withIdentifier: "toModels", sender: selectedMaker)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?)
    {
        if (segue.identifier == "toModels")
        {
            let objVC = segue.destination as! YOUR_NEXT_VIEWCONTROLLER
            objVC.strMaker = sender as? String ?? ""
        }
    }

Define in YOUR_NEXT_VIEWCONTROLLER

public var strMaker = ""

关于swift - 从 Collection View 执行segue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48922183/

相关文章:

ios - 在 NSUserDefaults 和 iOS Keychain 中存储用户凭据有什么区别

ios - NsMutable 不是 swift 中 [anyobject] 的子类型

c# - 修改新集合而不触及原始集合

arrays - Laravel 5 中 all() 和 toArray() 的区别

Python 等价于 R 的头尾函数

android - 如何设置 View 的背景颜色

IOS - DispatchQueue.main.asyncAfter(deadline : . now()) 和 perform(_:with:afterDelay:) 之间的区别,延迟为 0

swift - Swift 中的嵌套类型 - 好的做法是什么?

java - 双括号初始化 - 优点

python - django 在模板中显示上下文数据而不通过 url 调用 View