我试图从AvengersViewController发送charName字符串到CharViewController。
我在AvengersViewController中使用集合视图。 CharName是CharViewController中的标签。
我正在尝试的工作与表视图完美,但我无法使用collectionViews工作...
我使用“lastItemSelectedA”来表示我的复仇者阵列中的标签索引。数据传递工作...我无法使用第一个segue传递collectionViewItem的索引,因此,使其为null。通过使用默认值0,我已经能够注意到它确实有效,但是,当按下单元格时,它不会更改lastItemSelectedA的值但是...之后或者至少它不会更新变量。
我已经尝试过至少5个来自堆栈解决方案的实现。
extension AvengersViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
lastItemSelectedA = indexPath.item
//self.performSegue(withIdentifier: "openToCharA", sender: indexPath.item)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let identifier = segue.identifier else { return }
switch identifier {
case "openToCharA":
if let destination = segue.destination as? CharViewController {
destination.charName = avengers[lastItemSelectedA ?? 0].name
}
//destination.sounds = sounds
//guard let indexPath = collectionView.indexPathsForSelectedItems else {return}
//let sounds = fallen[lastItemSelectedF!].sounds
default:
print("unexpected segue identifier")
}
}
如果调用prepare(for segue
,那么你已经从集合视图单元(而不是从控制器)连接了segue。
在这种情况下删除
var lastItemSelectedA : Int
和
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
lastItemSelectedA = indexPath.item
//self.performSegue(withIdentifier: "openToCharA", sender: indexPath.item)
}
并从sender
参数获取集合视图单元格的索引路径
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "openToCharA" {
let cell = sender as! UICollectionViewCell
let indexPath = collectionView.indexPath(for: cell)!
let destination = segue.destination as! CharViewController
destination.charName = avengers[indexPath.item].name
}
}
在这种情况下,强制展开选项是很好的。如果所有内容都正确连接,代码一定不会崩溃,如果一切都显示出设计错误。