storyboard搭建项目_Swift - 使用storyboard创建表格视图(TableViewController)
(本文代碼已升級至Swift4)
項目創建完畢后,默認是使用 ViewController 作為主界面視圖。下面通過樣例演示,如何使用 TableViewController 作為主界面視圖,同時演示如何在 storyboard 中設置表格及內部單元格樣式。
功能如下:
1,程序運行后即為表格頁面
2,表格內容為“行號:內容”
3,點擊單元格可以切換勾選與取消勾選狀態
效果圖如下:
詳細步驟:
1,刪掉 storyboard現有的視圖界面。然后從對象庫中拖入一個 TableViewController到場景中。同時將其 Attributes 面板中的 Is Initial View Controller 選中。
2,新建一個類 MainController.swift,繼承自 UITableViewController
3,將場景中的 TableViewController與新建的 MainController進行綁定。選中主界面,然后再 Identity面板中將 CustomClass的 Class屬性設置為 MainController即可。
4,選中單元格(TableViewCell),在 Attributes面板中設置 Identifier屬性為“maincell”(供代碼中使用)。
同時將 Accessory屬性設置為 Checkmark(表示單元格尾部為勾號)
5,從對象庫中拖入一個 Label控件到 cell中,用于顯示內容。同時選中這個 Label,在 Attributes面板中設置 Tag的值為 1000,供代碼中獲取標簽。
6,MainController.swift
import UIKit
class MainController: UITableViewController {
var tasks:[String] = ["今天任務","明天任務","后天任務"]
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func tableView(_ tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return tasks.count
}
override func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "maincell",
for: indexPath)
//獲取label
let label = cell.viewWithTag(1000) as! UILabel
//設置label內容
label.text = "\(indexPath.row):\(tasks[indexPath.row])"
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//獲取cell
let cell = tableView.cellForRow(at: indexPath)!
//根據原先狀態,改變勾選或取消勾選狀態
if cell.accessoryType == UITableViewCellAccessoryType.none {
cell.accessoryType = UITableViewCellAccessoryType.checkmark
}else{
cell.accessoryType = UITableViewCellAccessoryType.none
}
//取消選中狀態
tableView.deselectRow(at: indexPath, animated: true)
}
}
7,上述操作完畢后會發現,表格頂著最上面不好看。我們可以在頭部添加一個 Navigation Controller 導航控制器。即選中 storyboard中的主界面,然后從 XCode的頂部菜單選擇 Editor-> Embed In-> Navigation Controller。
最后,選擇主界面(Main Controller Scene)的 Navigation Item,將 title設置為“任務列表” :
總結
以上是生活随笔為你收集整理的storyboard搭建项目_Swift - 使用storyboard创建表格视图(TableViewController)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ASP木马实验(I春秋)
- 下一篇: storyboard搭建项目_Story