在分組表中,每個分組就是一個 section;在索引表中,每個索引也是一個 section。
首先在 XIB 檔案中拖入一個 tableView,把它的 dataSource 與 delegate 連接到 File's Owner:
@interface Hello_WorldViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>{
}
上述程式碼讓類別遵循兩個協定:資料來源提供繪製表所需的所有資料,委派則用於設定表視圖的外觀。
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.listData.count;
}
此方法用來指明該 section 有幾個表項,預設 section 值為 1。
-(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = @"simpleIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if(cell == nil)
{
cell = [[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:simpleTableIdentifier];
}
NSUInteger row = [indexPath row];
cell.text = [self.listData objectAtIndex:row];
return cell;
}
此函式用來繪製 cell:第一個參數代表發起繪製的表視圖,第二個參數是 indexPath,透過它可取得 section 與 row。
表視圖在 iPhone 上一次只能顯示有限的幾行,但資料量可能很大。若為每一行資料都配置一個 cell,開銷將非常龐大。
由於有些 cell 目前正在顯示、有些則否,當一個 cell 滾出螢幕時,另一個 cell 就會從另一側滾入。若讓滾入的 cell 重用滾出螢幕的 cell,系統就不必為建立或刪除新 cell 而浪費空間與時間。我們用 identifier 來標記每個 cell,呼叫 dequeueReusableCellWithIdentifier: 檢查可重用佇列中是否已有相同標記的 cell:若有就直接使用,若沒有則回傳 nil,此時才建立新的 cell。
-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSUInteger section = [indexPath row];
NSString *rowValue = [self.listData objectAtIndex:section];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"你選擇的是"
message:rowValue delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
[alertView show];
}
上述方法表示點擊一個 cell 時觸發,會依所選列顯示對應內容。
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 100;
}
上述方法依 indexPath 指定每個 cell 的高度。