一、要使用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; }