如何将Swift Struct中的数据展示到UITableView?
解决方案
你的问题核心是没有从agentsReference数组中取出对应行的Agent对象,而是错误使用了未初始化的agentProperties变量(它默认是nil,自然访问不到name属性)。按以下步骤修改即可:
- 移除无用的
agentProperties : Agent?变量,你不需要它。 - 在
cellForRowAt方法中,通过indexPath.row从agentsReference数组获取当前行对应的Agent实例,再提取它的name属性赋值给单元格标签。
修改后的AgentListVC完整代码:
import UIKit class AgentListVC: UIViewController { var agentsReference = ValorantReferenceApp().agents @IBOutlet var tableView: UITableView! override func viewDidLoad() { tableView.delegate = self tableView.dataSource = self super.viewDidLoad() } } extension AgentListVC: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return agentsReference.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as! AgentCellVC // 获取当前行对应的Agent实例 let currentAgent = agentsReference[indexPath.row] // 将name赋值给标签 cell.agentNameLAbel.text = currentAgent.name return cell } }
额外注意:确保AgentCellVC类中确实存在名为agentNameLAbel的UILabel Outlet,并且已经在Storyboard/XIB中完成关联,否则会触发运行时错误。
内容的提问来源于stack exchange,提问作者7mach
相关产品推荐
相关产品推荐

