以编程方式将数据源分配给UITableView,而不调用数据源方法



我有tableview,它有两个部分,每个部分有一行。我想在点击按钮时填写tableview数据。在viewDidLoad中,我隐藏了tableView。单击按钮I,将datasourcedelegate分配给tableview,并取消隐藏tableview,但未调用其datasource方法。

以下是代码:

@IBAction func btnShowAction(_ sender: Any) {
tableView.delegate = self
tableView.dataSource = self
tableView.isHidden = false
}
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return ((tableView.frame.size.height / 2) - 20)
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if(section == 0) {
return "Section 1"
}
else {
return "Section 2"
}
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 20
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let tableViewCell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as! TableViewCell
tableViewCell.lblText.text = "abc"
return tableViewCell
}

当视图加载(例如viewDidLoad()(时,时间数据源方法将在内部调用reloadData(),但在您单击按钮的情况下,我们需要显式调用reloadData()来更新表视图,因为视图已经加载。你的代码应该是这样的,

@IBAction func btnShowAction(_ sender: Any) {
tableView.delegate = self
tableView.dataSource = self
tableView.reloadData()
tableView.isHidden = false
}

这将重新加载表视图的行和节。希望能有所帮助。

最新更新