You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iOS开发:Swift中如何从模型动态填充Label字段?

实现表格条目详情页的解决方案

问题背景

我已经通过API获取数据,借助Model文件和内置JSON解析器搭建了表格,现在想实现用户点击表格中的标题后,查看该条目的更多信息。API返回的数据格式如下:

[
  {
    "userId": 1,
    "id": 1,
    "title": "delectus aut autem",
    "completed": false
  },
  {
    "userId": 1,
    "id": 2,
    "title": "quis ut nam facilis et officia qui",
    "completed": false
  },
  ...
]

我知道需要添加一个title_details_ViewController.swift,但不清楚具体要写哪些代码,也不知道如何和Model文件关联。


具体实现步骤

1. 创建详情视图控制器

  • 新建Cocoa Touch Class,命名为title_details_ViewController,继承自UIViewController
  • 在Storyboard中添加一个新的ViewController,设置其Class为title_details_ViewController,并给它设置唯一的Storyboard ID(比如TitleDetailsVC)
  • 在详情页面添加所需UI控件:展示userId、id、title、completed状态的UILabel,通过IBOutlet将这些Label关联到title_details_ViewController.swift中

2. 确保Model文件正确解析数据

你的Model文件(比如Todo.swift)需要对应API字段,示例代码如下:

struct Todo: Codable {
    let userId: Int
    let id: Int
    let title: String
    let completed: Bool
}

3. 给详情控制器传递选中的Model数据

在title_details_ViewController.swift中添加接收数据的属性:

var selectedTodo: Todo!

回到表格所在的视图控制器,在tableView(_:didSelectRowAt:)方法中获取选中的Todo实例,跳转并传递数据:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    // 替换yourTodoArray为你实际存储Todo数据的数组名称
    let todo = yourTodoArray[indexPath.row]
    guard let detailsVC = storyboard?.instantiateViewController(withIdentifier: "TitleDetailsVC") as? title_details_ViewController else {
        return
    }
    detailsVC.selectedTodo = todo
    navigationController?.pushViewController(detailsVC, animated: true)
}

4. 在详情页面填充UI数据

在title_details_ViewController.swift的viewDidLoad方法中,将传递的Todo数据赋值给对应Label:

override func viewDidLoad() {
    super.viewDidLoad()
    
    // 替换以下Label名称为你实际关联的IBOutlet名称
    userIdLabel.text = "用户ID:\(selectedTodo.userId)"
    taskIdLabel.text = "任务ID:\(selectedTodo.id)"
    titleLabel.text = "任务标题:\(selectedTodo.title)"
    completedStatusLabel.text = "完成状态:\(selectedTodo.completed ? "已完成" : "未完成")"
}

内容的提问来源于stack exchange,提问作者Kyle Essenmacher

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 12:18:21