看板 KnucklesNote
作者 Knuckles (站長 那克斯)
標題 [Xcode][Swift3] 手動加入 TableView 元件
時間 2017-04-01 Sat. 18:35:31
依照這篇
[Xcode][Swift3] 使用 TableView 產生列表頁 - KnucklesNote板 - Disp BBS
使用 TableViewController 建立一個列表頁後
若是想在列表上方,加上其他不會隨列表捲動的元件,例如 ScrollView
會發現沒有辦法,ScrollView 只能放在 TableView 裡面
會隨著列表一起捲動
要讓 ScrollView 固定在上方不會被捲動的話
要使用 ViewController 後再手動加入 TableView 元件
重新建立一個專案試試看
一開始使用「Single View Application」產生的專案
預設就有一個 ViewController 了
點選 ViewController 後,點「Editor」/「Embed In」/「Navigation Controller」
就可以幫 ViewController 加上 Navigation Controller
拉一個我們想要固定在上方的 ScrollView
在 ScrollView 加上 上、左、右為 0 以及高度為 36 的 Constraints
不要勾選 Constrain to margins,Update Frames 選「Items of New Constraints」
拉一個 TableView 進來
在 TableView 加上 上下左右為 0 的 Constraints
注意上方是要與 ScrollView 的距離為 0
不要勾 Constrain to margins,Update Frames 選「Items of New Constraints」
在 TableView 的屬性檢視器,修改 Prototype Cells 的數目為 1
在 TableViewCell 的屬性檢視器,輸入 Identifier 為「TableViewCell」
使用 Assistant editor 按著 Ctrl 將 TableView 拉到程式碼中
名稱輸入 tableView
產生一個連結 TableView 的成員函數 tableView
@IBOutlet weak var tableView: UITableView!
切回 Standard editor,編輯程式檔 ViewController.swift
將 class ViewController: UIViewConstroller { 這行改為
class ViewController: UIViewConstroller, UITableViewDataSource, UITableViewDelegate {
讓類別繼承 UITableViewDataSource 與 UITableViewDelegate
修改成員函數 viewDidLoad(),加上
tableView.dataSource = self
tableView.delegate = self
加上三個 TableView 的 delegate 成員函數
func numberOfSections(in tableView: UITableView) ->Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 20
}
internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath)
cell.textLabel?.text = "測試標題 \(indexPath.row)"
return cell
}
執行看看
捲動時上方的 ScrollView 可以固定住了
列表上方加上分隔線
想要在列表上方也顯示一條分隔線的話
在成員函數 viewDidLoad() 裡加上
// 上方加上分隔線
let frame = CGRect(x: 0, y: 0, width: self.tableView.frame.size.width, height: 1 / UIScreen.main.scale)
let line: UIView = UIView(frame: frame)
self.tableView.tableHeaderView = line
line.backgroundColor = self.tableView.separatorColor
執行結果
加上下拉更新
使用 TableViewController 時,有內建 refreshControl
手動加上 TableView 的話就沒有了,不過可以自己加上去
修改 ViewController.swift
新增成員變數 refreshControl
var refreshControl = UIRefreshControl()
新增成員函數 loadData()
func loadData() {
//開始載入資料...
print("load data")
// 載入完資料後...
if(self.refreshControl.isRefreshing) {
self.refreshControl.endRefreshing()
}
}
這邊省略從網路下載資料的程式,只有在 Console 顯示 "load data"
當載入完資料後要將 refreshControl 關閉
在成員函數 viewDidLoad() 中加上
refreshControl.backgroundColor = UIColor.clear
refreshControl.tintColor = UIColor.black
refreshControl.attributedTitle = NSAttributedString(string: "更新資料")
refreshControl.addTarget(self, action: #selector(loadData), for: UIControlEvents.valueChanged)
self.tableView.addSubview(refreshControl)
執行結果
--
--
※ 作者: Knuckles 時間: 2017-04-01 18:35:31