【发布时间】:2021-08-02 04:33:09
【问题描述】:
我正在使用 UITableViewCell 来显示数据。当视图加载时,数据是空的,但是一旦 api 调用完成,我想重新初始化 UITableViewCell 以便数据可以出现。我正在使用以下代码,但TableView.reloadData() 不会重新初始化 UITableViewCell,因此不会重新加载数据。
TableViewCell
class TableViewCell: UITableViewCell {
var Info: Information?
let Chart = LineChartView(frame: .zero)
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
print("initialized")
self.contentView.addSubview(Chart)
Chart.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
Chart.topAnchor.constraint(equalTo: self.contentView.topAnchor, constant: 10),
Chart.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor, constant: -10),
Chart.rightAnchor.constraint(equalTo: self.contentView.rightAnchor, constant: -10),
Chart.leftAnchor.constraint(equalTo: self.contentView.leftAnchor, constant: 10),
])
let data = ChartHelpers().makeLineChart(data: Info?.Values ?? [Double]())
Chart.data = data
self.contentView.layoutIfNeeded()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
视图控制器
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var Info: Information?
let TableView = UITableView(frame: .zero)
override func viewDidLoad() {
super.viewDidLoad()
APICall()
setUpUI()
}
func setUpUI() {
view.addSubview(TableView)
TableView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
TableView.topAnchor.constraint(equalTo: view.topAnchor),
TableView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
TableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
TableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
])
self.TableView.register(TableViewCell.self, forCellReuseIdentifier: "Chart")
TableView.delegate = self
TableView.dataSource = self
TableView.reloadData()
view.layoutIfNeeded()
}
func APICall() {
API().fetchInformation(Name: "John Doe") { (Info) in
//success connecting to api
DispatchQueue.main.async {
self.Info = Info
self.TableView.reloadData()
}
} failure: { (error) in
//failure connecting to api
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = TableView.dequeueReusableCell(withIdentifier: "Chart", for: indexPath) as! TableViewCell
tableView.rowHeight = 300
cell.Info = self.Info
return cell
}
}
【问题讨论】:
标签: ios swift api uitableview reloaddata