2016-09-23 4 views
2

При использовании FirebaseUI я пытаюсь реализовать пользовательскую ячейку для своих данных из firebase. Я хотел бы иметь несколько пользовательских меток в клетке, как так:FirebaseUI: фатальная ошибка: неожиданно обнаружена нуль при развертывании необязательного значения Использование раскадровки и метки пользовательского интерфейса

enter image description here

Вот что мой вид коллекции контроллер выглядит следующим образом:

import UIKit 
import Firebase 
import FirebaseDatabaseUI 
private let reuseIdentifier = "Cell" 

class ShowDogsCollectionViewController: UICollectionViewController { 

let firebaseRef = FIRDatabase.database().reference().child("dogs") 
var dataSource: FirebaseCollectionViewDataSource! 

override func viewDidLoad() { 
    super.viewDidLoad() 

    self.dataSource = FirebaseCollectionViewDataSource(ref: self.firebaseRef, cellClass: DogCollectionViewCell.self, cellReuseIdentifier: reuseIdentifier, view: self.collectionView!) 

    self.dataSource.populateCell { (cell: UICollectionViewCell, obj: NSObject) -> Void in 
     let snap = obj as! FIRDataSnapshot 
     let dogCell = cell as! DogCollectionViewCell 

     dogCell.backgroundColor = UIColor.green 
     print(snap.childSnapshot(forPath: "name")) 

     // The line below should set the label text for one of the labels on our custom UICollectionCell Class, however it unwraps to nil. 
     // fatal error: unexpectedly found nil while unwrapping an Optional value 
     // dogCell.dogAge.text = "woot" 

    } 
    self.collectionView?.dataSource = self.dataSource 
} 
override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
} 
} 

И это мой пользовательский класс клеток. Реальный Простой.

import UIKit 

class DogCollectionViewCell: UICollectionViewCell { 

    @IBOutlet weak var dogName: UILabel! 
    @IBOutlet weak var dogAge: UILabel! 
    @IBOutlet weak var dogToy: UILabel! 

} 

Я разместил код на GitHub здесь:

https://github.com/thexande/firebaseCustomUICollectionViewCellDemo

, а также видео с описанием проблемы здесь:

https://youtu.be/q_m-bgofOb4

Я определена через ответы на этот вопрос, и все, кажется, связаны с XIB, а не с доской. Разве это невозможно с рассказом?

Спасибо всем !!!

ответ

1

Хорошо. Поэтому, пытаясь понять какое-то время, я понял это.

Вы должны установить DataSource по self.dataSource = FirebaseCollectionViewDataSource(ref: self.firebaseRef, prototypeReuseIdentifier: reuseIdentifier, view: self.collectionView!)

один с prototypeReuseIdentifier. В противном случае вы не используете свой DogCollectionViewCell, но создаете новый экземпляр UICollectionViewCell, который не имеет элементов метки. Вот почему вы получаете нуль, пытаясь установить его свойство .text.

Затем вы можете установить возраст по вашему коду dogCell.dogAge.text = "woot".

enter image description here

override func viewDidLoad() { 
    super.viewDidLoad() 

    self.dataSource = FirebaseCollectionViewDataSource(ref: self.firebaseRef, prototypeReuseIdentifier: reuseIdentifier, view: self.collectionView!) 

    self.dataSource.populateCell { (cell: UICollectionViewCell, obj: NSObject) -> Void in 
     let snap = obj as! FIRDataSnapshot 
     let dogCell = cell as! DogCollectionViewCell 
     dogCell.backgroundColor = UIColor.green 

     dogCell.dogAge.text = "woot" 

    } 
    self.collectionView?.dataSource = self.dataSource 
} 

Чтобы получить значения оснастки:

let nameSnap = snap.childSnapshot(forPath: "name")    
dogCell.dogName.text = nameSnap.value! as? String 

enter image description here