TableviewController基礎

表示圖是顯示錶數據的試圖對象,它是UITableView類的一個實例。表中的每個課件的行都是UITableViewCell類實現。因此,表示圖是顯示錶中可見部分對象,表試圖單元負責顯示錶中的一行。

表示圖並不負責存儲表中的數據。他們只存儲足夠繪製當前可見行的數據。表示圖從遵循UITableViewLegate協議的對象獲取配置數據,從遵循UITableViewDataSource協議的對象獲得行數據。

表示圖分爲兩種基本樣式。一種是分組表。另一類是索引表。表中的每個部分被稱爲數據源中的分區(section)。

實現一個簡單的表

1、打開程序創建一個Simple_TableViewController的項目,單擊大打開  Simple_TableViewController.xib,View窗口應該已經打開,因此,在庫中找到TableView,並將它拖到View窗口中即可。

2、將TableView關聯到文件,只需連接到File‘s Owner 。這樣控制器類就成了此表的數據源和委託。  

3、打開Simple_TableViewController.h,添加下面代碼

#import <UIKit/UIKit.h>

@interface Simple_TableViewController:UIViewController<UITableViewDelegate,UITableViewDataSource>

{

NSArray *listData;

}  

@property(nonatomic,retain) NSArray *listData;

@end

 

 

4、在Simple_TableViewController.m裏添加。頭文件不寫了。

@synthesize listData;

-(void)viewDidLoad{

NSArray *array=[[NSArray alloc]initWithObjects:@"dsda",@"erwerwe",@"dsada",nil];

self.listData=array;

[array release];

[super viewDidLoad];

 

//自動生成的代碼我急不寫了

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

return [self.listData count];

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

static NSString * SimpleTableIdentifier= @"simpleTableIdentifier";

UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifiter:SimpleTableIdentifier];

if(cell==nil){

cell=[[UITableViewCell alloc]initWithFrame:CGRectZero reuseIdentifier:SimpleTableIdentifier] autorelease];

}

NSUInterger row=[indexPath row];

cell.text=[listData objectAtIndex:row];

return cell;

}

 

}

 

第一個方法是tableView:
numberOfRowsInSection:,表使用它來查看指定分區中有多少行。正如你所希望的,默認的分區
數量爲1,此方法用於返回組成列表的表分區中的行數。只需返回數組中數組項的數量即可。

 

下一個方法可能需要一些解釋,讓我們更仔細地看一下此方法:

當表視圖需要繪製其中一行時,則會調用此方法。你會注意到此方法的第二個參數是一個
NSIndexPath實例。表視圖正是使用此機制把分區和行綁定到一個對象中的。要從NSIndexPath中
獲得一行或一個分區,只需要調用行方法或分區方法就可以了,這兩個方法都返回一個int值。

      

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章