Swift UITableView 使用的简单介绍

来源:互联网 发布:理光复印机刷卡软件 编辑:程序博客网 时间:2024/04/29 00:48

刚开始学习Swift时感觉很艰难,熟练一段时间后觉得还行,下边我把我在学习Swift中遇到的关于UITableView实用上的一些心得分享给大家

使用Swift故事板实现UITableView方式有两种

第一种

第一步:在对象库中拖出View Controller

第二步:添加TableView控件然后添加TableViewCell控件

树形结构如图所示:

第三步:新建一个继承UIViewController的Controller文件并于故事板中的ViewController关联

第四步:实现UITableView的数据源(dataSource)和代理(delegate)

UITableView需要一个数据源(dataSource)来显示数据,UITableView会向数据源查询一共有多少行数据以及每一行显示什么数据等。没有设置数据源的UITableView只是个空壳。凡是遵守UITableViewDataSource协议的OC对象,都可以是UITableView的数据源。

通常都要为UITableView设置代理对象(delegate),以便在UITableView触发一下事件时做出相应的处理,比如选中了某一行。凡是遵守了UITableViewDelegate协议的OC对象,都可以是UITableView的代理对象。一般会让控制器充当UITableView的dataSource和delegate

 

继承UITableViewDataSource必须实现的两个方法:

//设置tableView的数据行数 return数据源的行数

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int

//配置tableView 的单元格 return UITableViewCell

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell

 

数据源和代理中有很多方法上边这两个是必须重写的

例如:

=======DataSource中的方法=======

//返回单元格的高

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat

=======Delegate中的方法=======

//返回有多少个Sections

func numberOfSectionsInTableView(tableView: UITableView) -> Int

// 返回每一个Sections的Ttitle的高度

func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat

//设置每一个Section的样子

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?

 

第五步:让故事板中的UITableView在Controller中关联

第六步(容易被忽略也最重要的一步):

在viewDidLoad()方法中实现委托:mainTableView.delegate = self mainTableView.dataSource = self

凡是实现了tableview的代理协议,和数据源协议的类都可以被一个UITableView指定成它的委托,和数据源 ,假如你的用A类实现了上面两个协议(协议中@request 协议方法 都要实现 ),你可以指定.tableView.delegate=(A类所创建的对象) ,只是你的这个类本身就实现了这两个协议,所以 它可以等于self

 

到这简单的UITableView实用就基本完成了

 

第二种(相对第一种简单太多,但是看情景使用,有时候还必须使用第一种方式)

 

直接在故事板中拖出TableViewController,新建一个继承UITableViewController的Controller,并与故事板中的TableViewController关联。

实现下边两个基本方法

//设置tableView的数据行数 return数据源的行数

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int

//配置tableView 的单元格 return UITableViewCell

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell

 

当我们按着command键点UITableViewController进去看的时候可以发现UITableViewController已经实现了UITableView数据源和协议

 

0 0
原创粉丝点击