Swift开发IOS-UITableView

来源:互联网 发布:underscore.js源码 编辑:程序博客网 时间:2024/05/16 06:53

下面通过代理的方法来填充和操作UITableView,需要让UIViewController使用UITableViewDelegate和UITableViewDataSource:


查看UITableViewDataSource协议文件,可以看到UITableViewDataSource有两个方法是必须重写的(required),其它方法是可选(optional):


上面两个require方法必须在ViewController类中实现,否则程序会一直报错:其中func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int 函数的返回值是UITableView的item的数量,可以根据section返回每一节(Section)的Item的数量,要是只有一节(Section),则返回全部Item的数量;func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell,UITableViewCell即为每一个Item的布局,indexPath的类型是NSIndexPath,可以获得节序号(indexPath.section)以及这一节(Section)中某一Item的行号(indexPath.row)通过这两个参数返回对应的UITableViewCell。

实现UITableView的步骤:

(一).声明并且托管UITableView的delegate和dataSource


(二).重写UITableViewDelegate和UITableViewDataSource中的方法


[附]其中涉及到的Person.swift和PersonDataSet.swift文件如下:

 

[效果]


[其他常用功能]

1.UITableViewCell的选择事件

当UITableView中的某一个UITableViewCell被点选的时候,会调用UITableViewDelegate中的func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)-> Void 方法:


2.实现UITableView的编辑功能(Delete和Insert)

2-1 指定每一indexPath的cell是否可以编辑,以及编辑类型


2-2 实现删除和插入的功能

首先在ViewController界面添加一个UIButton,用来切换UITableView的编辑状态:

  • 声明编辑按键UIButton:
  • 添加按键到ViewController:
  • UITableView状态切换:                                                                                 
重写UITableView的func tableView(tableView: UITableView, commitEditingStyle editingStyle:UITableViewCellEditingStyle, forRowAtIndexPath indexPath:NSIndexPath) -> Void方法,实现UITableView的删除和插入功能:

[效果]


[说明1]
UITableView继承自UIScrollView,有Plain(不分组)和Grouped(分组)两种样式:UITableViewStyle.Plain简单的充满整个UITableView的frame,若不设置组间距的话,默认组与组之间没有间距;UITableViewStyle.Grouped分组样式,默认组与组之间有一定的距离。

[说明2]
系统提供的UITableViewCellStyle有4种样式,提供了三个属性:textLabel(主文本标签),detailTextLabel(二级文本标签)以及imageView(图片视图)
  • UITableViewCellStyle.Default(注意:Default不支持detailTextLabel这个属性)                                               
  • UITableViewCellStyle.Subtitle(增加了对detailTextLabel的支持,位于textLabel)             
  • UITableViewCellStyle.Value1(textLabel居左显示,detailTextLabel居右显示)                 
  • UITableViewCellStyle.Value2(注意:不支持imageView,textLabel居左显示为蓝色       )
[说明3]
通过cell.accessoryType可以设置UITableViewCell最右侧的样式,系统提供的UITableViewCellAccessoryType有5种:


  • UITableViewCellAccessoryType.None(不显示任何标记按钮)                                       
  • UITableViewCellAccessoryType.DisclosureIndicator                                                         
  • UITableViewCellAccessoryType.DetailDisclosureButton                                                   
  • UITableViewCellAccessoryType.Checkmark                                                                     

  • UITableViewCellAccessoryType.DetailButton                                                                    

1 0
原创粉丝点击