【问题标题】:Swift: Could not cast value of type 'UITableViewCell' to a custom cell classSwift:无法将“UITableViewCell”类型的值转换为自定义单元格类
【发布时间】:2015-12-20 03:47:42
【问题描述】:

我正在开发 iOS 应用程序,它需要从 Firebase 中提取数据并显示在表格视图中。为了给它一个自定义设计,我创建了一个自定义表格视图单元格类。当我尝试显示 firebase 在“populateCellWithBlock”方法中返回的数据时,应用程序崩溃,显示此错误:

无法将“UITableViewCell”(0x10a73f9f0) 类型的值转换为“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
}
}

【问题讨论】:

  • 我没有从上面的代码中看到任何问题,你可以发布你的 RideTableViewCell 自定义类
  • cell的类型是什么?
  • @DanielT。单元格是“AnyObject”
  • 你是如何创建单元格的:原型单元格,带有 nib 的自定义类?您是否在界面生成器中为自定义单元格提供了 RideTableViewCell 自定义类属性?重用标识符是否匹配?
  • @MikeMcDonald 这是情节提要中的原型单元格,具有重用标识符。我已经检查过 - 是的,它与代码中的匹配。

标签: ios swift uitableview firebase


【解决方案1】:

这里是 FirebaseUI-iOS 的作者。

看起来问题是我们返回UITableViewCell 而不是RideTableViewCell,因为FirebaseTableViewDataSource 返回的单元格的默认类是UITableViewCell,而cellClass 属性是没有设置。

可以使用包含cellClass的构造函数版本来解决这个问题:

dataSource = FirebaseTableViewDataSource(ref: ref, cellClass: RideTableViewCell.self, cellReuseIdentifier: "rideCell", view: self.ridesTableView)

这将使我们能够将对象的适当转换版本返回给您。此外,为了解决在人口中静态了解细胞类型的问题,w 可以执行以下操作。

在 Objective-C 中这真的很简单,因为我们可以给块中的属性赋予不同的类型:

[self.dataSource populateCellWithBlock:^(YourCustomCellClass *cell, FDataSnapshot *snap) {
    // Populate cell as you see fit
}];

因为我们使用__kindof UITableViewCell 作为可用的参数(id 没有,所以在 XCode 7 之前),这种行为在任何版本的 XCode 中都可以正常工作,因为 XCode 要么接受“是的,这个类是UITableViewCell 的子类”(>= XCode 7)或“如果它是 id 我仍然可以向它发送消息,所以我会允许它”(

斯威夫特是一个不同的故事。虽然你认为你应该能够做到:

dataSource.populateCellWithBlock{ (cell: YourCustomClass, snapshot: FDataSnapshot) -> Void in
    // Populate cell as you see fit
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-30
    相关资源
    最近更新 更多