1、要使用UITableView必须用当前实现两个协议<UITableViewDataSource, UITableViewDelegate> UITableViewDataSource协议实现了数据加载的方法,UITableViewDelgate协议实现了UITableView外观设置,事件等方法。
03 | #import <UIKit/UIKit.h> |
05 | @interface RootViewController : UIViewController <UITableViewDataSource, UITableViewDelegate> |
08 | UITableView *_tableView; |
_tableView 私有全局变量用来保存 UITableView对象。
_listArray 私有全局变量用来存放 UITableView需要的数据。
2、创建UITableView
04 | UIView *view = [[UIView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame]; |
11 | _tableView = [[UITableView alloc] initWithFrame:view.bounds style:UITableViewStylePlain]; |
13 | _tableView.dataSource = self; |
15 | [self.view addSubview:_tableView]; |
17 | _listArray = [[UIFont familyNames] retain]; |
3、数据源方法
02 | - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { |
03 | return [_listArray count]; |
08 | - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { |
09 | static NSString *cellIdentifier = @ "cell" ; |
11 | UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: cellIdentifier]; |
14 | cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease]; |
17 | NSString *fontName = _listArray[indexPath.row]; |
18 | cell.textLabel.text = fontName; |
19 | cell.textLabel.textColor = [UIColor blueColor]; |
20 | cell.textLabel.font = [UIFont fontWithName:fontName size:12]; |
02 | _tableView.backgroundColor = [UIColor yellowColor]; |
08 | _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine; |
11 | UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 80)]; |
12 | headerView.backgroundColor = [UIColor redColor] |
16 | UILabel *headText = [[UILabel alloc] initWithFrame:CGRectMake(60, 0, 200, 80)]; |
18 | headText.text = @ "天晴朗,天晴朗天晴朗天晴朗!" ; |
20 | headText.numberOfLines = 0; |
22 | [headerView addSubview:headText]; |
27 | _tableView.tableHeaderView = headerView; |
34 | UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 80)]; |
36 | footerView.backgroundColor = [UIColor yellowColor]; |
38 | _tableView.tableFooterView = footerView; |
转http://my.oschina.net/wangdk/blog/150291