您应该使用添加了部分的 UITableView。有一个很好的教程here。
更新
首先,通过拖动到视图控制器上创建一个 UITableView。添加必要的约束,并生成原型单元。
将单元重用标识符设置为单元。
然后,Control 左键单击并将 tableView 拖动到 ViewController(顶部的黄色圆圈)。这样做两次并将其分配为 DataSource 和 Delegate。
打开助手编辑器并控制将tableView拖到类中以创建IBOutlet。然后在你的类声明中添加UITableViewDelegate:
class ViewController: UIViewController, UITableViewDelegate {
完成此操作后,创建两个新的空白 Swift 文件。文件,新建,文件。
标题一个文件 Section.swift 和另一个 SectionsData.swift。
在文件 Section.swift 中,添加此代码。
struct Section
{
var heading : String
var items : [String]
init(title: String, objects : [String]) {
heading = title
items = objects
}
}
您在这里定义了一个结构,以便以后可以获取数据。
在 SectionsData 文件中放入以下代码。您可以在此处编辑进入表格的内容。
class SectionsData {
func getSectionsFromData() -> [Section] {
var sectionsArray = [Section]()
let hello = Section(title: "Hello", objects: ["Create", "This", "To", "The"])
let world = Section(title: "World", objects: ["Extent", "Needed", "To", "Supply", "Your", "Data"])
let swift = Section(title: "Swift", objects: ["Swift", "Swift", "Swift", "Swift"])
sectionsArray.append(hello)
sectionsArray.append(world)
sectionsArray.append(swift)
return sectionsArray
}
}
在此文件中,您创建了一个类,然后创建了一个函数来保存和检索数据。
现在,在包含您的 tableview 的 IBOutlet 的文件中,创建以下变量。
var sections: [Section] = SectionsData().getSectionsFromData()
现在已经完成了艰苦的工作,是时候填充表格了。以下函数允许这样做。
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return sections.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return sections[section].items.count
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String?
{
return sections[section].heading
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
cell.textLabel?.text = sections[indexPath.section].items[indexPath.row]
return cell
}
你应该能够运行它并得到你想要的结果。您可以在提供数据时编辑单元格外观。例如,
cell.textLabel?.font = UIFont(name: "Times New Roman", size: 30)
只要确保像这样更改字体时,字符串名称的拼写是准确的。
我希望这会有所帮助。