首页 文章

在详细视图控制器中查看错误

提问于
浏览
1

我已经创建了模型类,并且我已经填充了一些静态图像和文本UICollectionView,但是当用户触摸单元格时,当我打印或在标签上显示时,它在视图控制器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委托

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
    }

}

1 回答

  • 3

    EDIT

    调用 performSegueWithIdentifier 时,使用 poke 作为发件人而不是 self

    performSegueWithIdentifier("pokeSegue", sender: poke)
    

    ORIGINAL ANSWER

    我假设您使用 UICollectionViewCell 来触发segue .

    如果是这样, let poke = sender as? Pokemon 将始终返回 false 并被跳过,因为 sender 将是触发segue的 UICollectionViewCell 而不是 Pokemon 的实例 .

    您可以创建一个可以存储Pokemon对象的新类型 UICollectionViewCell ,也可以只使用单元格的 tag 属性来存储引用的Pokemon的索引 .

    此值可从 collectionView(_ collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) 方法配置 .

    然后在 prepareForSegue 方法中,您必须将sender对象强制转换为相关的 UICollectionView 类型,并使用您定义的信息检索Pokemon .

相关问题