我的目标是执行从 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/