数据源协议与委托协议
UITableViewDataSource
数据源协议主要为表视图提供数据,主要方法如下
| 方法 | 返回类型 | 说明 |
|---|---|---|
| func tableView(UITableView, cellForRowAt: IndexPath) | UITableViewCell | 为表视图单元格提供数据,必须实现 |
| tableView(UITableView, numberOfRowsInSection: Int) | Int | 返回某个节中的行数,必须实现 |
| tableView(UITableView, titleForHeaderInSection: Int) | String | 返回节头的标题 |
| tableView(UITableView, titleForFooterInSection: Int) | String | 返回节脚的标题 |
| numberOfSections(in: UITableView) | Int | 返回节的个数 |
| sectionIndexTitles(for: UITableView) | [String]? | 返回表示图节索引标题 |
UITableViewDelegate
委托协议主要主要用来设定表视图中节头和节脚的标题,以及一些动作事件,主要方法如下
| 方法 | 返回类型 | 说明 |
|---|---|---|
| tableView(UITableView, didSelectRowAt: IndexPath) | 单元格响应事件 | |
| tableView(UITableView, accessoryButtonTappedForRowWith: IndexPath) | 扩展视图响应事件 |
简单表视图
UIViewController根视图控制器实现表视图
步骤
-
创建一个iOS工程
从对象库中拖入一个TableView到storyboard文件中,并将TableView覆盖整个View
打开Table View的属性检查器,将PrototypeCells的值设为1,注意不要添加多个,否则会发生错误;此时Table View会添加一个Table View Cell。
打开Table View Cell的属性检查器,设置Identifier属性。
注册UITableViewDataSource和UITableViewDelegate协议
编写代码实现功能
实现
//
// ViewController.swift
// TableViewDemo
//
// Created by Michael on 2016/10/26.
// Copyright © 2016年 Michael. All rights reserved.
//
import UIKit
class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
//全部数据
var listItems: NSArray!
override func viewDidLoad() {
super.viewDidLoad()
//读取资源文件数据
let listPath = Bundle.main.path(forResource: "team", ofType: "plist")
self.listItems = NSArray(contentsOfFile: listPath!)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//返回列表每行的视图
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//根据Identifier找到Cell
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomId", for: indexPath)
let row = indexPath.row
let rowDict = self.listItems[row] as! NSDictionary
cell.textLabel?.text = rowDict["name"] as? String
cell.detailTextLabel?.text = "123"
let imagePath = String(format: "%@.png", rowDict["image"] as! String)
cell.imageView?.image = UIImage(named: imagePath)
cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator
return cell
}
//返回条目数目
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.listItems.count
}
//响应条目点击事件
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("点击事件")
}
}










