ios - 详细 View Controller 中的 Segue 错误

标签 ios swift segue

我已经创建了模型类,并使用一些静态图像和文本填充了 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/

相关文章:

ios - 按两个属性排序

swift - 如何将 SCNFloor 的属性与 Swift 和 Scenekit 一起使用?

ios - UITableViewCell类中的dequeueReuseableCellwithIdentifier方法如何使用?

ios - 从一个 tableView 创建不同的 segue

Swift 将数据从 TabBarController 传递到 TableViewController

ios - 在 segue 与 Swift 2.0 之间传递数据

ios - 如何将 Braintree Paypal 与 iOS 集成?

ios - iOS 上的 Bootstrap 3 表格响应背景颜色问题

ios - glGenTextures 返回现有纹理名称

objective-c - iOS RESTful POST调用在UIWebView中有效,但从线程调用时无效