UIKit 与 Interface Builder
ViewController、Storyboard、Auto Layout。
40 分钟
UIKit 与 Interface Builder
UIKit 是 iOS 传统的命令式 UI 框架:ViewController 驱动界面,Storyboard / XIB 可视化布局,Auto Layout 适配多尺寸。对照 /roadmaps/ios「UIKit」节点;老项目与部分系统扩展仍以 UIKit 为主。
学习目标
- 理解 MVC 在 UIKit 中的角色:ViewController 协调 View 与 Model
- 用代码或 Storyboard 创建界面,掌握 Auto Layout 约束
- 处理 TableView / CollectionView 列表展示
- 了解 UIKit 与 SwiftUI 的互操作(UIHostingController)
核心概念
ViewController 生命周期
import UIKit
class LessonListViewController: UIViewController {
private var lessons: [Lesson] = []
private lazy var tableView: UITableView = {
let tv = UITableView(frame: .zero, style: .plain)
tv.translatesAutoresizingMaskIntoConstraints = false
tv.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
tv.dataSource = self
tv.delegate = self
return tv
}()
override func viewDidLoad() {
super.viewDidLoad()
title = "课时列表"
view.backgroundColor = .systemBackground
view.addSubview(tableView)
NSLayoutConstraint.activate([
tableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
])
loadLessons()
}
private func loadLessons() {
lessons = [
Lesson(id: 1, title: "Swift 基础", completed: false),
Lesson(id: 2, title: "UIKit 布局", completed: true),
]
tableView.reloadData()
}
}
extension LessonListViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
lessons.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
var config = cell.defaultContentConfiguration()
config.text = lessons[indexPath.row].title
cell.contentConfiguration = config
return cell
}
}
viewDidLoad → viewWillAppear → viewDidAppear 是常见钩子;列表用 UITableView + DataSource / Delegate 模式。