【发布时间】:2019-04-15 15:29:18
【问题描述】:
我有一个表格栏,其中有 3 个独立的 MVC。第一个 MVC 是UITableView,我可以在其中搜索位置,它将显示 10 天的预测。第二个 MVC 也是一个 UITableView 存储我最喜欢的位置。我可以点击该位置,它会给我带来另一个UITableView,它会像第一个标签栏一样显示 10 天的预测。但是我得到一个 “线程 1:致命错误:在展开可选值时意外发现 nil” 我正在使用自定义原型单元格,就像第一个选项卡栏视图一样,它在那里工作得很好。
我的第一个标签栏 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
}
自定义原型单元格类似于:
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")
}
【问题讨论】:
-
你强制解开这个:
for parameters in timeSeries!.parameters。当有一个预期的timeseries但不存在时,那里可能有一个 nil 值会爆炸。您应该使用if let或guard let来解开timeseries -
检查
WeatherTemperatureLabel是否在情节提要中链接
标签: ios swift uitableview uilabel optional