TableView主要用于展现数据,相似于Android中的ListView。html
咱们能够经过两个方式使用TableView。第一种是直接使用TableView类。第二种是经过UITableViewController类。xcode
第一种方式主要是经过实例化一个UITableView类,而后将类实例添加到主界面,代码以下app
这样,一个简单的tableview就建立了,固然这个时候界面中是没有数据的。spa
运行结果以下:code
接下来为TableView添加数据。经过查看UITableView类的头文件可知道,该类有一个dataSource属性,属性遵照了UITableViewDataSource协议。htm
所以,该属性只接受类型为UITableViewDataSource的值。在这里咱们只须要令viewController遵照该协议便可,而后就能够将dataSource属性值设为self。继承
代码以下:get
这个时候xcode会有一个黄色的感叹号,由于咱们尚未实现协议里面的方法。it
要为TableView提供数据,咱们必须至少实现下面的两个方法:io
- (NSInteger)tableView:() numberOfRowsInSection:()UITableView *tableViewNSIntegersection
- (UITableViewCell *)tableView:() cellForRowAtIndexPath:()UITableView *tableViewNSIndexPath *indexPath
第一个方法告诉TableView每一个section有多少行,第二个方法用于设置每一行的外观(View)是怎样的。TableView中每一行都是一个UITableViewCell类。
如今先把这两个方法实现一下。代码以下:
运行效果:
UITAbleViewDataSource中还有一个方法用来设置section,由于咱们没有实现这个方法,因此section默认值是0。
该方法是:
- (NSInteger)numberOfSectionsInTableView:()UITableView *tableView
经过实现这个方法修改section数量:
修改后运行效果:
使用UITableViewController建立Tableview
默认状况下每一个视图的控制器都是UIViewController,经过修改UIWindow类中的rootViewController属性的值能够改变这个行为。
所以下面的代码在appDelegate.m文件中的
- (BOOL)application:() didFinishLaunchingWithOptions:()UIApplication *applicationNSDictionary *launchOptions
方法中进行。
首先建立一个继承自UITableViewController的类。
类建立好后基本上就是在这个新建的类中实现上面的方法便可。由于UITableViewController类已经遵照了UITableViewDataSource协议。
并且UITableViewController里面已经有TableView的属性,所以咱们无需实例化UITableView。
MyTableViewController类中的代码:
最后将rootViewController设置为新创建的类:
运行结果: