从集合视图执行segue

时间:2018-02-22 07:54:10

标签: swift collections view segue

我的目标是从集合视图单元格执行segue到视图控制器。在下一个视图控制器中我有声明

 let selectedCar = CarViewController()

 if selectedCar.selectedMaker == "a"

我知道使用其他类执行segue的方法,但不知道如何使用集合视图执行。我使用了ifPath语句的indexPath。 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")
    }

1 个答案:

答案 0 :(得分:0)

尝试编辑

setInterval()
  

在YOUR_NEXT_VIEWCONTROLLER中定义

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 ?? ""
        }
    }
相关问题