在iOS中,MVC(Model-View-Controller)是一种常见的软件设计模式,它通过将应用程序分成三个主要组件来帮助管理复杂性:模型、视图和控制器。下面是一个简单的MVC示例,展示了如何在iOS中实现这个模式。
struct Todo {
var title: String
var isCompleted: Bool
}
import UIKit
class TodoViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var todos: [Todo] = [
Todo(title: "Buy groceries", isCompleted: false),
Todo(title: "Walk the dog", isCompleted: false),
Todo(title: "Read a book", isCompleted: true)
]
let tableView = UITableView()
override func viewDidLoad() {
super.viewDidLoad()
title = "Todos"
view.addSubview(tableView)
tableView.frame = view.bounds
tableView.dataSource = self
tableView.delegate = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return todos.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let todo = todos[indexPath.row]
cell.textLabel?.text = todo.title
cell.accessoryType = todo.isCompleted ? .checkmark : .none
return cell
}
}
// 控制器代码在上面的 TodoViewController 中已经包含
override func viewDidLoad() {
super.viewDidLoad()
// 初始化数据和视图
}