I have created the model class and with some static images and text I have populated the UICollectionView, but when the user touches the cell it shows an error in view controller 2 when I print or show it on a label. Below is the code.
Any suggestion?!
This is the model class
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
}
}
This is segue func in viewcontroller 1
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)
}
In 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
}
}
EDIT
Use poke
as the sender instead of self
when calling performSegueWithIdentifier
:
performSegueWithIdentifier("pokeSegue", sender: poke)
ORIGINAL ANSWER
I assume that you are using an UICollectionViewCell
to trigger the segue.
If so, the let poke = sender as? Pokemon
let poke = sender as? Pokemon
will always returns false
and be skipped because the sender
will be the UICollectionViewCell
that triggered the segue and not an instance of Pokemon
.
You can either create a new type of UICollectionViewCell
that can store a Pokemon object or simply use the tag
property of the cells to store the index of the referenced Pokemon.
This value is configurable from the collectionView(_ collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath)
method.
Then in the prepareForSegue
method you have to cast the sender object to the relevant UICollectionView
type and retrieve the Pokemon with the information you defined.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.