整体代码运行良好,我将 pulltorefreshControl
用于 UITableView
。每当我通过 pulltoRefresh
刷新它时,它都会给我 Fatal error: Index out of range: file Swift/ContiguousArrayBuffer.swift, line 444
在 cellForRowAt 函数的 let dic = Appdata![indexPath.row]
上突出显示错误。
我的代码很简单,只是从 JSON 响应中获取数据。
在顶部声明:var Appdata : [Appointment]? = []
JSON 响应代码:
func appointmentCall(_ someDateTime:Date) {
self.Appdata?.removeAll()
DataProvider.main.serviceGetAppointment(date: someDateTime, callback: {success, result in
do{
if(success){
let decoder = JSONDecoder()
let response = try decoder.decode(ResponseData.self, from: result! as! Data)
self.Appdata = response.appointments
self.tableView.reloadData()
return true
}else{
self.Appdata?.removeAll()
self.tableView.reloadData()
return false
}
}catch let error {
print(error as Any)
return false
}
})
}
下拉刷新功能:
@objc func refresh(_ sender: AnyObject) {
// refresh tableview datasource
DispatchQueue.main.async {
sender.beginRefreshing()
self.Appdata?.removeAll()
self.appointmentCall(appointDate)
self.refreshControl.endRefreshing()
}
}
TableView 代码:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Appdata?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "AppointmentTableViewCell", for: indexPath) as! AppointmentTableViewCell
let dic = Appdata![indexPath.row]
cell.rightView.backgroundColor = dic.backgroundColorLight?.toColor() ?? ("#cfd8dc").toColor()
cell.rightView.layer.applySketchShadow()
cell.topLabel.text = dic.projectName
cell.midLabel.text = dic.subTitle
cell.leftView.backgroundColor = dic.backgroundColorDark?.toColor() ?? ("#556f7b").toColor()
cell.rightLabel.text = dic.projectDistrict
cell.leftTopLabel.text = dic.appointmentHour
cell.leftBotLabel.text = dic.controlHour
cell.botLabel.text = dic.projectFirmName
return cell
}