我正在开发 iOS 应用,该应用需要从 Firebase 中提取数据并显示在表格 View 中。为了给它一个自定义设计,我创建了一个自定义 TableView 单元格类。当我尝试显示 firebase 在“populateCellWithBlock”方法中返回的数据时,应用程序崩溃,显示此错误:
Could not cast value of type 'UITableViewCell' (0x10a73f9f0) to 'EFRideSharing.RideTableViewCell' (0x108117f20).
dataSource = FirebaseTableViewDataSource(ref: ref, cellReuseIdentifier: "rideCell", view: self.ridesTableView)
dataSource.populateCellWithBlock
{ (cell,snapshot) -> Void in
let tvc: RideTableViewCell = cell as! RideTableViewCell
let snapshot: FDataSnapshot = snapshot as! FDataSnapshot
tvc.toLabel.text = snapshot.value["time"] as? String
}
有什么想法可以让它发挥作用吗?
更新:附加代码
class RideTableViewCell: UITableViewCell {
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var toLabel: UILabel!
@IBOutlet weak var fromLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
最佳答案
这里是 FirebaseUI-iOS 的作者。
看起来问题是我们返回的是 UITableViewCell
而不是 RideTableViewCell
,因为 FirebaseTableViewDataSource 返回的单元格的默认类当未设置
为 cellClass
属性时,UITableViewCell
。
您可以使用包含cellClass
的构造函数版本来解决此问题:
dataSource = FirebaseTableViewDataSource(ref: ref, cellClass: RideTableViewCell.self, cellReuseIdentifier: "rideCell", view: self.ridesTableView)
这将使我们能够将对象的适当转换版本返回给您。此外,为了解决静态了解群体中细胞类型的问题,w 可以执行以下操作。
在 Objective-C 中,这非常简单,因为我们只需为 block 中的属性指定不同的类型即可:
[self.dataSource populateCellWithBlock:^(YourCustomCellClass *cell, FDataSnapshot *snap) {
// Populate cell as you see fit
}];
因为我们使用 __kindof UITableViewCell
作为可用的参数(如果没有,则使用 id
,所以在 XCode 7 之前),这种行为在任何版本的 XCode 中都能按预期工作,因为XCode 将接受“是的,这个类是 UITableViewCell 的子类”(>= XCode 7)或“如果它是 id
我仍然可以向它发送消息,所以我会允许它”( <= XCode 6.4)。
Swift 是一个不同的故事。虽然您认为您应该能够做到:
dataSource.populateCellWithBlock{ (cell: YourCustomClass, snapshot: FDataSnapshot) -> Void in
// Populate cell as you see fit
}
并获得合理的预制单元版本。也就是说,我一直收到错误消息,指出将 AnyObject
与 YourCustomClass
进行比较时方法签名不匹配,并将其归结为 Apple 问题与 __kindof
,这是我所知道的记录最少的功能之一。如果有人对为什么会出现这种情况有任何想法,或者知道更好的文档,我很想听听这是从哪里来的(或者它是否在 XCode 7 的 GM 版本中得到修复)。
关于ios - Swift:无法将类型 'UITableViewCell' 的值转换为自定义单元格类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32729187/