ios - UITableView 没有从 Segue 加载数据
问题描述
我有一个用户登录的序列,然后他们被带到通过 segue 显示 UITableView 的视图。我试图在成功登录后将数据从登录屏幕注入表。
在登录视图中...
func transitionToHome() {
print("Hey you logged in!")=
performSegue(withIdentifier: "loginSuccess", sender: self)
self.navigationController!.setNavigationBarHidden(false, animated: false)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let vc = segue.destination as! ViewController
vc.models = [(title: "title", note: "Note")]
}
在主屏幕视图中
@IBOutlet var table: UITableView!
@IBOutlet var label: UILabel!
@IBOutlet weak var newNoteButton: UIButton!
var models: [(title: String, note: String)] = []
override func viewDidLoad() {
super.viewDidLoad()
table.delegate = self
table.dataSource = self
title = "Notes"
}
我尝试在 viewDidLoad 以及 viewDidAppear 和 viewWillAppear 中调用 table.reloadData()。两者都没有奏效。
我还在 viewDidLoad 中打印出模型,我看到数据已正确传递给视图控制器。但是,当从 segue 加载视图控制器时,我无法让表加载这些数据。
解决方案
如果您在 viewDidLoad() 中正确建模数据打印,您应该能够使用 dataSource 实现中的数据配置表格视图单元格。请参阅下面的 dataSource 实现的示例扩展。确保为情节提要中的原型单元提供重用标识符。
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
var content = cell.defaultContentConfiguration()
content.text = "This is a cell primary text"
cell.contentConfiguration = content
return cell
}