在iOS下編寫TableView是很容易的。
最簡單的TableView
比如實現這樣的效果:
首先建立一個view based application:
接著,修改view xib檔案,將TableView拖拽到view中:
右側圖是拖拽後的效果。然後是建立關聯,需要建立兩個:
- dataSource,串連到資料來源,這樣TableView才知道顯示資料的資訊
- delegate,串連到TableView delegate,回調它來和應用的邏輯部分互動
都串連到Controller即可,即file’s owner:
然後,需要讓Controller實現兩個protocol:
@interface TableDemoViewController : UIViewController<UITableViewDelegate,UITableViewDataSource>
其中UITableViewDataSource要求兩個方法必須實現:
這裡要先在h檔案中聲明用於dataSource的資料結構,這是使用的是固定數組:
NSArray *dataItems;
}
@property(nonatomic,retain) NSArray *dataItems;
然後,在m檔案中執行個體化數組:
@synthesize dataItems;
…
- (void)viewDidLoad {
dataItems= [[NSArray alloc] initWithObjects:@"張三",@"李四",nil];
[super viewDidLoad];
}
現在可以實現上面的兩個方法了:
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [dataItems count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *simpleTableIdentifier=@"SimpleTableIdentifier";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if(cell==nil){
cell=[[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:simpleTableIdentifier] autorelease];
}
NSUInteger row=[indexPath row];
cell.textLabel.text=[dataItems objectAtIndex:row];
return cell;
}
這裡要注意,我寫的例子是參照《iPhone開發基礎教程》,裡面的寫法是:
cell.text=…
已經不建議使用了:
在TableView條目前添加圖片
如果想實現這樣的效果:
這裡的圖片,來自項目自身,可以將圖片拖拽到項目的Resources目錄下:
然後在代碼中只需增加一行:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *simpleTableIdentifier=@"SimpleTableIdentifier";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if(cell==nil){
cell=[[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:simpleTableIdentifier] autorelease];
}
NSUInteger row=[indexPath row];
cell.textLabel.text=[dataItems objectAtIndex:row];
cell.imageView.image=[UIImage imageNamed:@"tag.png"];
return cell;
為TableView增加互動功能
只需增加一個函數即可,這是UITableViewDelegate protocol中的一個函數,用於在選擇表條目後回調。
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSLog(@">>choose:%@",[dataItems objectAtIndex:[indexPath row]]);
}
這樣當點擊條目後,日誌中就會列印條目中的資料。
http://marshal.easymorse.com/archives/3511