在使用 FirebaseUI 时,我试图为来自 Firebase 的数据实现自定义单元格。我想在单元格中有一些自定义标签,如下所示:
这是我的 Collection View Controller 的样子:
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
以及此处描述问题的视频:
我已经挑选了对这个问题的回答,所有似乎都涉及 XIB 而不是 Storyboard。 Storyboard不可能做到这一点吗?
谢谢大家!!!
最佳答案
好的。所以在尝试了一段时间后我想通了。
您需要通过 self.dataSource = FirebaseCollectionViewDataSource(ref: self.firebaseRef, prototypeReuseIdentifier: reuseIdentifier, view: self.collectionView!)
设置数据源
带有 prototypeReuseIdentifier 的那个。否则,您不是在使用 DogCollectionViewCell
,而是在创建一个没有标签元素的 UICollectionViewCell 的新实例。这就是为什么您通过尝试设置其 .text
属性而得到 nil 的原因。
然后你可以通过代码设置年龄 dogCell.dogAge.text = "woot"
。
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
关于ios - FirebaseUI: fatal error :使用 Storyboard和 UI 标签展开可选值时意外发现 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39651640/