UITableView中的協議中有兩大協議分別是:
<UITableViewDelegate>
<UITableViewDataSource>比較重要
協議的執行流程:(注意:每個協議完整執行之後纔會走下個流程)
1.先走有多少個section的協議:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return self.arr.count;
}
2.設定section的高度的協議
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 1;
}
3.設定section的title的協議:
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section;
- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section;
4.多少行的協議
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 1;
}
5.設置行高協議:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 220;
}
6.走cell的協議(這裏注意重用池的概念,每個row只對應一個cell,一般做項目都自定義cell,這裏CustomCell就是我自定義的)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//1.定義重用池的名字,
static NSString *cellIdentify =@"cell1";
//2.從重用池中取不用的cell,看能不能取出來,
//從以cell1命名的重用池裏取
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify];
//如果沒有,新建一個cell,並放到重用池cell1裏
if (!cell) {
cell = [[[CustomCellalloc] initWithStyle:UITableViewCellStyleSubtitlereuseIdentifier:cellIdentify] autorelease];//要加autorelease
}
//3.設置背景顏色,在if外面
[cell setBackgroundColor:[UIColorgreenColor]];
//取字典裏的值
NSDictionary *dic = [_tableArrayobjectAtIndex:indexPath.row];
NSString *name = [dic objectForKey:@"name"];
cell.label.text = name;
return cell;//返回cell
7.點擊觸發事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *dictionary = [_tableArrayobjectAtIndex:indexPath.row];
//創建第二個界面,跳過去
SecondViewController *sec = [[SecondViewControlleralloc] init];
sec.dic = dictionary;
[sec release];
}
8.特殊的協議:
(1)返回值類型是數組的協議
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
- (NSArray *)indexPathsForRowsInRect:(CGRect)rect;
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView;
(2)返回值類型是UIView的協議
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section;
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section;
- (UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
//第幾個分區的高度是多少
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section;