ios - Swift:无法将类型 'UITableViewCell' 的值转换为自定义单元格类

标签 ios swift uitableview firebase

我正在开发 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
}

并获得合理的预制单元版本。也就是说,我一直收到错误消息,指出将 AnyObjectYourCustomClass 进行比较时方法签名不匹配,并将其归结为 Apple 问题与 __kindof ,这是我所知道的记录最少的功能之一。如果有人对为什么会出现这种情况有任何想法,或者知道更好的文档,我很想听听这是从哪里来的(或者它是否在 XCode 7 的 GM 版本中得到修复)。

关于ios - Swift:无法将类型 'UITableViewCell' 的值转换为自定义单元格类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32729187/

相关文章:

ios - UITableView 中重复使用的单元格会导致发生不需要的操作

ios - 如何检查计时器是否小于某个值然后运行函数?

ios - 从 didFinishLaunchingWithOptions 终止应用程序

ios - XCode 7 项目重命名导致 XCTestCase 中出现 'Cannot import module being compiled' 错误

ios - 围绕 UITableView 部分插入

ios - uitableview 数据源以错误的顺序快速重新加载

ios - Swift iOS - 如何将直接从 TableViewCell 的子类中获取的值传递给 TableView 的 didSelectRow?

iphone - UITableView 中的附件 View : view doesn't update

ios - 有条件地更改后退按钮图像,iOS

ios - 警告 : Incompatible pointer types assigning to 'NSMutableArray *' from 'NSArray<NSString *> * _Nullable'