模型数组中的 UITableView 和单元格
Posted
技术标签:
【中文标题】模型数组中的 UITableView 和单元格【英文标题】:UITableView and Cells from Model Array 【发布时间】:2019-05-04 07:22:46 【问题描述】:我遇到了一些我不太明白的事情,从一些测试来看,表格单元格的生成似乎是在页面加载和 Alamofire 请求之前发生但在之后却没有发生。
如果您在下面看到,我正试图在参考专业人士后将它送到我们博物馆的出境货物查看位置:
import Alamofire
import SwiftyJSON
class ShipmentProSearchResultsTableViewController: UITableViewController
var pronumber:String = ""
var shipments = [Shipment]()
typealias JSONStandard = [String: AnyObject]
override func viewDidLoad()
super.viewDidLoad()
fetchShipments()
func fetchShipments()
let parameters: Parameters = ["pro_number": pronumber]
let todoEndpoint: String = "OURHOST/shipments/api/details/pro"
Alamofire.request(todoEndpoint, method: .get, parameters: parameters)
.responseJSON response in
if response.result.isSuccess
let shipmentJSON : JSON = JSON(response.result.value!)
for (index, subJson):(String, JSON) in shipmentJSON
let proNumber = subJson["proNumber"].int
let consigneeName = subJson["consignee"]["name"].string
let shipment = Shipment(proNumber: proNumber!, consigneeName: consigneeName!)
self.shipments.append(shipment)
print(self.shipments)
else
print("Could not get results")
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
return shipments.count
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
let cell = tableView.dequeueReusableCell(withIdentifier: "ShipmentCell", for: indexPath)
let shipment = shipments[indexPath.row]
cell.textLabel?.text = "Hello"
cell.detailTextLabel?.text = "\(shipment.proNumber)"
return cell
现在我打印self.shipments
,得到以下结果:
[OakRidgeArchaeologicalRepositoryDispatcher.Shipment(proNumber: 471008276, consigneeName: "A1 CHICAGO INSTITUTE OF THE ARTS")]
所以我知道数据正在适当地传递给模型。我还会注意到情节提要中的表格视图单元格标识符正确设置为ShipmentCell
。但是查询之后,我的表中什么也没有弹出。
我正在使用 Swift 4。
【问题讨论】:
【参考方案1】:您应该在更新源字段后重新加载tableView
。
func fetchShipments()
let parameters: Parameters = ["pro_number": pronumber]
let todoEndpoint: String = "OURHOST/shipments/api/details/pro"
Alamofire.request(todoEndpoint, method: .get, parameters: parameters)
.responseJSON response in
if response.result.isSuccess
let shipmentJSON : JSON = JSON(response.result.value!)
for (index, subJson):(String, JSON) in shipmentJSON
let proNumber = subJson["proNumber"].int
let consigneeName = subJson["consignee"]["name"].string
let shipment = Shipment(proNumber: proNumber!, consigneeName: consigneeName!)
self.shipments.append(shipment)
tableView.reloadData() //<-------add this.
print(self.shipments)
else
print("Could not get results")
【讨论】:
这是正确的,tableView 需要重新加载。但是它必须发生在主线程上。所以把@ocanal 的建议包装在DispatchQueue.main.async self.tableView.reload
以上是关于模型数组中的 UITableView 和单元格的主要内容,如果未能解决你的问题,请参考以下文章
问:如何更改 UITableView 中的单元格大小,以显示所有标签?
如何编写 UI 测试来测试单击 UITableView 中的第一个单元格时图像是不是存在?
UITableView 中的奇怪行为 - 一个单元格显示不同