Swift 使用日期时,在可重用单元格中找到带有日期选择器的Nil
我得到了以下代码:Swift 使用日期时,在可重用单元格中找到带有日期选择器的Nil,swift,datepicker,tablecell,Swift,Datepicker,Tablecell,我得到了以下代码: var cell = DatePickerTableViewCell() func updateDueDateLabel() { cell.dueDateLabel.text = dueDateFormatter.string(from: cell.dueDatePickerView.date) } let dueDateFormatter: DateFormatter = { let formatter = DateFormatter() f
var cell = DatePickerTableViewCell()
func updateDueDateLabel() {
cell.dueDateLabel.text = dueDateFormatter.string(from: cell.dueDatePickerView.date)
}
let dueDateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "dd-MM-YYYY"
return formatter
}()
电池为:
class DatePickerTableViewCell: UITableViewCell {
@IBOutlet var dueDatePickerView: UIDatePicker!
@IBOutlet var dueDateLabel: UILabel! }
其中日期选择器和标签位于可重复使用的单元格中
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 && indexPath.row == 1 {
cell = tableView.dequeueReusableCell(withIdentifier: "datePicker") as! DatePickerTableViewCell
}
if indexPath.section == 0 && indexPath.row == 0 {
cell = tableView.dequeueReusableCell(withIdentifier: "label") as! DatePickerTableViewCell
cell.selectionStyle = .none
}
return cell
}
当我尝试调用函数UpdatedEdateLabel时,我收到一条错误消息,它在展开时发现nil,我无法找出错误所在。cell.dueDateLabel正在工作,因此是格式化程序或日期选择器导致了错误
如果我对更新标签的func进行注释,屏幕上会显示表格、标签和日期选择器。您有两个自定义单元格:
datepicker
和label
。但它令人困惑,因为在您对DatePickerTableViewCell
的定义中,这种类型的单元格同时具有日期选择器和标签
在尝试更改cell.dueDateLabel.text之前,必须确保cell
是带有UILabel的单元格
并且,在尝试加载文本之前,请确保已加载datePicker视图。我似乎发现了错误,我将调用函数的位置从viewdidload更改为单元格加载后,我假设这是因为datePicker尚未加载。您的标签是否连接到故事板?如果是,则需要显示tableViewCell
代码的其余部分。另外,您的updateDatelabel
方法中的cell
是什么?不相关,但您的日期格式可能是错误的。它应该是yyyy
,除非你真正指的是基于周的日历。你的方法updateDatelabel
在哪里?你在哪里调用它呢?它位于我的类中,我是从视图调用它的。但这不是问题,我尝试在tableview之外使用一个标签,并尝试将其设置为=dueDateFormatter.string(from:cell.dueDatePickerView.date),但它仍然崩溃