ios - 使用自定义单元格在 UITableView 中展开 UILabel 时 Swift 崩溃

标签 ios swift uitableview uilabel option-type

我有一个表格栏,其中有 3 个独立的 MVC。第一个 MVC 是一个 UITableView,我可以在其中搜索位置并将显示 10 天的预报。第二个 MVC 也是一个 UITableView 存储我最喜欢的位置。我可以点击该位置,它会给我带来另一个 UITableView,它显示 10 天的预报,就像第一个标签栏一样。但是我得到一个“线程 1: fatal error :在展开可选值时意外发现 nil” 我正在使用自定义原型(prototype)单元格,就像第一个选项卡栏 View 一样,它在那里工作得很好。 enter image description here

我的第一个标签栏 mvc 代码如下:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "WeatherDataCell", for: indexPath)

let weatherCell = timeSeries[indexPath.row]
if let wc = cell as? WeatherTableViewCell {
    wc.timeSeries = weatherCell
}

return cell
}

自定义原型(prototype)单元看起来像这样:

class WeatherTableViewCell: UITableViewCell {

    @IBOutlet weak var WeatherImageView: UIImageView!
    @IBOutlet weak var WeatherTimeLabel: UILabel!
    @IBOutlet weak var WeatherTemperatureLabel: UILabel!
    @IBOutlet weak var WeatherWindLabel: UILabel!
    @IBOutlet weak var WeatherPrecipitationLabel: UILabel!

    var timeSeries : TimeSeries? {
        didSet {
            updateUI()
        }
    }

    func updateUI() {
        for parameters in timeSeries!.parameters {
        if parameters.name == "t" {
            let temperature = parameters.values[0]
            WeatherTemperatureLabel.text? = "\(temperature) °C" // <- works for the first MVC but crashes on the second MVC even though i can print out the temperature
        }
    }
}

秒MVC中的func基本上看起来和第一个一样所以我不明白为什么它崩溃了,它应该有数据。

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "DetailedWeatherCell", for: indexPath) as! WeatherTableViewCell

let weatherCell = timeSeries[indexPath.row]        
let wc = cell
wc.timeSeries = weatherCell

return cell

}

为清楚起见添加了额外的代码(我的 FavoriteDetailedTableViewController 类):

    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.register(WeatherTableViewCell.self, forCellReuseIdentifier: "DetailedWeatherCell")
}

最佳答案

我认为您忘记更改 FavoriteDetailedTableViewController 中原型(prototype)单元格的标识符。在此 TableViewController 中将其更改为

enter image description here

它应该可以工作。

其次你可能忘了在这里设置你的单元格类

enter image description here

同时从 viewDidLoad 中删除这一行

self.tableView.register(WeatherTableViewCell.self, forCellReuseIdentifier: "DetailedWeatherCell")

关于ios - 使用自定义单元格在 UITableView 中展开 UILabel 时 Swift 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53270147/

相关文章:

ios - 如果我们点击背景中的任何地方,除了快速点击 popView 之外,如何删除 popView

ios - 为什么 sizeThatFits() 返回的尺寸太小?

iphone - 自定义uitableview单元格问题

ios - 使用非公共(public) API LSApplicationWorkspace 拒绝应用程序

ios - 为 iPhone X 处理自定义标签栏

ios - NSSortDescriptor 与关系

ios - 如何在不使用 sudo 的情况下从终端窗口关闭我的互联网连接?

ios - UIAlertController 在生成警报 View 时出错

ios - UITableViewCell 分隔符插图不起作用

ios - 调用scrollToRowAtIndexPath时的SIGABRT