我正在尝试将 charName 字符串从 AvengersViewController 发送到 CharViewController。
我在 AvengersViewController 中使用 Collection View 。 CharName 是 CharViewController 中的一个标签。
我正在尝试的工作与 TableView 完美配合,但我无法使用 collectionViews 使其工作...
我正在使用“lastItemSelectedA”来指示我的复仇者数组中标签的索引。数据的传递有效......我无法让 collectionViewItem 的索引与第一个 segue 一起传递,因此,使其为空。通过使用默认值 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
被调用然后你从 Collection View cell(而不是从controller)连接segue。
在这种情况下删除
<罢工>罢工>
<罢工>var lastItemSelectedA : Int
罢工><罢工>罢工>
和
<罢工>罢工>
<罢工>func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
lastItemSelectedA = indexPath.item
//self.performSegue(withIdentifier: "openToCharA", sender: indexPath.item)
}
罢工><罢工>罢工>
并从 sender
获取 Collection View 单元格的索引路径参数
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
}
}
在这种情况下,强制解包可选值是可以的。如果一切都正确连接,则代码不能崩溃,如果崩溃,则表明存在设计错误。
关于ios - 使用 collectionviewCell 使用 override func prepare 传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55441486/