我已经创建了模型类,并使用一些静态图像和文本填充了 UICollectionView,但是当用户触摸单元格时,当我打印或在标签上显示它时,它会在 View Controller 2 中显示错误。下面是代码。
有什么建议吗?!
这是模型类
import Foundation
class Pokemon {
private var _name: String!
private var _pokedexId: Int!
// Setter And Getter
var name : String {
return _name
}
var pokedexId: Int {
return _pokedexId
}
// Initializer to initialize the data
init(name : String, pokedexId: Int) {
self._name = name
self._pokedexId = pokedexId
}
}
这是 viewcontroller 1 中的 segue func
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "pokeSegue" {
if let detailVC = segue.destinationViewController as? ViewController2 {
if let poke = sender as? Pokemon {
detailVC.pokemon = poke
}
}
}
UICollectionView 委托(delegate)
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let poke: Pokemon!
if inSearchMode {
poke = filteredPokemon[indexPath.row]
} else {
poke = pokemon[indexPath.row]
}
print(poke.name)
performSegueWithIdentifier("pokeSegue", sender: self)
}
在viewController2中
import UIKit
class ViewController2: UIViewController {
var pokemon: Pokemon!
var receviceingString : String!
@IBOutlet weak var label: UILabel!
override func viewDidLoad() {
print(pokemon.name) //unexpectedly found nil while unwrapping an Optional value
}
}
最佳答案
编辑
使用 poke
作为发件人而不是 self
打电话时 performSegueWithIdentifier
:
performSegueWithIdentifier("pokeSegue", sender: poke)
原始答案
我假设您使用的是 UICollectionViewCell
触发 segue。
如果是这样,let poke = sender as? Pokemon
将始终返回 false
并被跳过,因为 sender
将是 UICollectionViewCell
触发了 segue 而不是 Pokemon
的实例.
您可以创建一个新类型的 UICollectionViewCell
可以存储 Pokemon 对象或简单地使用 tag
单元格的属性来存储引用的口袋妖怪的索引。
此值可从 collectionView(_ collectionView: UICollectionView,
cellForItemAtIndexPath indexPath: NSIndexPath)
中配置方法。
然后在prepareForSegue
方法,您必须将发件人对象转换为相关的 UICollectionView
使用您定义的信息键入并检索 Pokemon。
关于ios - 详细 View Controller 中的 Segue 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35840636/