標籤:
一 建立表格,並把表格添加到控制器
UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];//建立表格 指定表格的寬高為self.view.bounds就是鋪滿全屏 設定表格樣式為分組樣式UITableViewStyleGrouped 還有一個樣式為UITableViewStylePlain 普通樣式
tableView.dataSource = self;//設定表格顯示資料的資料來源,這個必須遵循UITableViewDataSource這個協議,如果不遵循這個協議會調用不到綁定資料的方法
[self.view addSubview:tableView]; 把表格添加到控制器
二 設定表格綁定資料和每行cell綁定的方法
#pragma mark - 資料來源方法
#pragma mark 一共有多少組(section == 地區\組)
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView //numberOfSenctionsInTableView方法為反回資料有多少組,並把這個組傳給反回行方法,這個是自動調用的
{
// NSLog(@"numberOfSections");
return 3; 返回3組
}
#pragma mark 第section組一共有多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section //numberOfRowsInSection為返回多少行的方法
{
senction // 這參數為上面方法傳過來的第幾組,這裡接怍到第幾組後,把相對應有幾行返回過去
}
#pragma mark 返回每一行顯示的內容(每一行顯示怎樣的cell)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//這裡接收第幾組第幾行的索引(indexPath.Senction,indexPath.Row),然後定義UITableViewCell 通過設定cell的相應屬性並把cell返回,這樣就完成了每一行顯示什麼資料
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
cell.textLabel.text = text;
return cell;
}
#pragma mark 第section組顯示的頭部標題
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return @"表頭";
}
#pragma mark 第section組顯示的尾部標題
- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
{
return @"結尾";
}
#pragma mark 返回表格右邊的顯示的索引條
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView //該方法為顯示索引條,物別注意動態數組的添加方式
{
NSMutableArray *titles = [NSMutableArray array];
for (Province *p in _allProvinces) {
[titles addObject:p.header];
}
return titles;
}
UITableView基本屬性應用