下面的例子是对来自 We ❤ Swift 的a longer post 的改编和简化。这就是它的样子:
创建一个新项目
它可以只是普通的单视图应用程序。
添加代码
用以下代码替换 ViewController.swift 代码:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// Data model: These strings will be the data for the table view cells
let animals: [String] = ["Horse", "Cow", "Camel", "Sheep", "Goat"]
// cell reuse id (cells that scroll out of view can be reused)
let cellReuseIdentifier = "cell"
// don't forget to hook this up from the storyboard
@IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Register the table view cell class and its reuse id
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)
// (optional) include this line if you want to remove the extra empty cell divider lines
// self.tableView.tableFooterView = UIView()
// This view controller itself will provide the delegate methods and row data for the table view.
tableView.delegate = self
tableView.dataSource = self
}
// number of rows in table view
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.animals.count
}
// create a cell for each table view row
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// create a new cell if needed or reuse an old one
let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!
// set the text from the data model
cell.textLabel?.text = self.animals[indexPath.row]
return cell
}
// method to run when table view cell is tapped
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("You tapped cell number \(indexPath.row).")
}
}
阅读代码内的 cmets 以了解发生了什么。亮点是
- 视图控制器采用
UITableViewDelegate和UITableViewDataSource协议。
-
numberOfRowsInSection 方法确定表格视图中有多少行。
-
cellForRowAtIndexPath 方法设置每一行。
- 每次点击一行时都会调用
didSelectRowAtIndexPath 方法。
向情节提要添加表格视图
将UITableView 拖到您的视图控制器上。使用自动布局固定四个边。
连接奥特莱斯
Control 从 IB 中的 Table View 拖动到代码中的 tableView 出口。
完成
就是这样。您现在应该可以运行您的应用了。
这个答案已经用 Xcode 9 和 Swift 4 测试过
变化
行删除
如果你想让用户删除行,你只需要在上面的基本项目中添加一个方法。请参阅this basic example 了解如何操作。
行间距
如果您希望行之间有间距,请参阅this supplemental example。
自定义单元格
表格视图单元格的默认布局可能不是您需要的。 Check out this example 帮助您开始制作自己的自定义单元格。
动态单元格高度
有时您不希望每个单元格都具有相同的高度。从 iOS 8 开始,很容易根据单元格内容自动设置高度。 See this example 为您提供入门所需的一切。
进一步阅读