swift构建课程表详细代码
时间: 2023-11-12 21:00:30 浏览: 40
以下是一个简单的 Swift 代码示例,用于构建课程表:
```swift
import UIKit
class ViewController: UIViewController {
// 声明一个 UITableView 用于显示课程表
let tableView = UITableView()
// 声明一个数组来存储所有课程的名称
let courses = ["语文", "数学", "英语", "物理", "化学", "生物"]
override func viewDidLoad() {
super.viewDidLoad()
// 设置 UITableView 的 frame,以便它填充整个屏幕
tableView.frame = view.bounds
// 将当前视图控制器设置为 UITableView 的数据源和代理
tableView.dataSource = self
tableView.delegate = self
// 注册 UITableViewCell
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
// 将 UITableView 添加到当前视图控制器的视图中
view.addSubview(tableView)
}
}
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// 返回课程数组中的元素数量
return courses.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// 从 UITableView 中获取一个可重用的 UITableViewCell,并设置其文本标签为课程数组中对应索引的元素
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = courses[indexPath.row]
return cell
}
}
extension ViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// 当用户点击 UITableViewCell 时,弹出一个 UIAlertController 显示课程名称
let courseName = courses[indexPath.row]
let alert = UIAlertController(title: courseName, message: nil, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "确定", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
}
}
```
这个示例代码中,我们首先创建一个 `UITableView` 并设置其 frame,然后将当前视图控制器设置为其数据源和代理。在数据源方法中,我们返回了 `courses` 数组中的元素数量,并从 `UITableView` 中获取一个可重用的 `UITableViewCell` 并设置其文本标签为对应索引的课程名称。在代理方法中,我们设置了当用户点击 `UITableViewCell` 时,弹出一个 `UIAlertController` 显示课程名称。