一、要使用UITableView必须用当前实现两个协议<UITableViewDataSource, UITableViewDelegate> UITableViewDataSource协议实现了数据加载的方法,UITableViewDelgate协议实现了UITableView外观设置,事件等方法。 数组
// RootViewController.h 测试控制器 #import <UIKit/UIKit.h> @interface RootViewController : UIViewController <UITableViewDataSource, UITableViewDelegate> { @private UITableView *_tableView; NSArray *_listArray; } @end
_tableView 私有全局变量用来保存 UITableView对象。
_listArray 私有全局变量用来存放 UITableView须要的数据。 app
二、建立UITableView
测试
- (void)loadView { // 建立一个基本视图 UIView *view = [[UIView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame]; // 设置为当前控制器的默认视图 self.view = view; // 释放视图 [view release]; // 建立tableview _tableView = [[UITableView alloc] initWithFrame:view.bounds style:UITableViewStylePlain]; // 设置数据源 注意这个方法设置不对,没有数据哦! _tableView.dataSource = self; // 添加到默认控制器中 [self.view addSubview:_tableView]; // tableview 获取系统默认字体数组 retain 是必须的,否则会报错哦!由于_listArray 必须接管这个数组对象 _listArray = [[UIFont familyNames] retain]; }三、数据源方法
// 设置行数 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [_listArray count]; } // 设置行数据 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *cellIdentifier = @"cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: cellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease]; } NSString *fontName = _listArray[indexPath.row]; cell.textLabel.text = fontName; cell.textLabel.textColor = [UIColor blueColor]; cell.textLabel.font = [UIFont fontWithName:fontName size:12]; return cell; }