只有一組時 通知tableview有幾個cell
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return datasource.count
}
不止一組時 通知tableview每一組有幾個cell
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return info[section].count
}
每個cell要顯示的內(nèi)容
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// 取得 tableView 目前使用的 cell
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as UITableViewCell
// 設(shè)置 Accessory 按鈕樣式
if indexPath.section == 1 {
if indexPath.row == 0 {
cell.accessoryType = .checkmark
} else if indexPath.row == 1 {
cell.accessoryType = .detailButton
} else if indexPath.row == 2 {
cell.accessoryType = .detailDisclosureButton
} else if indexPath.row == 3 {
cell.accessoryType = .disclosureIndicator
}
}
// 顯示的內(nèi)容
if let myLabel = cell.textLabel {
myLabel.text = "\(info[indexPath.section][indexPath.row])"
}
return cell
}
// 點選 cell 後執(zhí)行的動作
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// 取消 cell 的選取狀態(tài)
tableView.deselectRow(at: indexPath, animated: true)
let name = info[indexPath.section][indexPath.row]
print("選擇的是 \(name)")
}
// 點選 Accessory 按鈕後執(zhí)行的動作
// 必須設(shè)置 cell 的 accessoryType
func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
let name = info[indexPath.section][indexPath.row]
print("按下的是 \(name) 的 detail")
}
// 有幾組 section
func numberOfSections(in tableView: UITableView) -> Int {
return info.count
}
// 每個 section 的標(biāo)題
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let title = section == 0 ? "籃球" : "棒球"
return title
}