要進(jìn)行tableView的相關(guān)設(shè)置需要遵守以下兩個(gè)協(xié)議
@interface RootViewController()<UITableViewDelegate, UITableViewDataSource>
@end
初始化
//此處y軸設(shè)為64是44的NavigationBar+20的手機(jī)導(dǎo)航欄的高度
UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,64,414,736-64)];
tableView.delegate = self;
tableView.dataSource = self;
[self.view addSubview:tableView];
一般的tableView創(chuàng)建時(shí)寫這些內(nèi)容就差不多完成了
實(shí)現(xiàn)協(xié)議方法
#pragma mark 必須實(shí)現(xiàn)的方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
//此方法返回的是tableView的分區(qū)數(shù)
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowInSection:(NSInteger)section{
//此方法返回的是tableView不同分區(qū)的行數(shù)
return 10;
}
- (UITableViewCell *)tableView:(UITableView *)tableView CellForRowAtIndexPath:(NSIndexPath *)indexPath{
//此方法返回的是tableView的cell,tableView的cell使用的是重用機(jī)制,即創(chuàng)建有限個(gè)cell來(lái)應(yīng)對(duì)無(wú)限個(gè)條目,
//當(dāng)一個(gè)cell即將在視圖中出現(xiàn)時(shí),從重用池中調(diào)用一個(gè)cell來(lái)使用,如果沒(méi)有則創(chuàng)建,對(duì)應(yīng)的當(dāng)一個(gè)cell已經(jīng)從視
//圖中消失時(shí),將其放入重用池
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
//identifier必須上下一致,這是在重用池中取用cell的標(biāo)識(shí)
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
}
return cell;
}
此處創(chuàng)建的是系統(tǒng)提供的cell,我們實(shí)際工作中一般都會(huì)使用自定義cell。
創(chuàng)建cell除了以上方法之外還可以使用注冊(cè)模式
[tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
//提前注冊(cè)cell的類型,自定義cell或者系統(tǒng)cell都可以這樣注冊(cè)
在返回cell的方法中
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
在前面注冊(cè)之后,后面取用的方法中需附帶設(shè)置indexPath
#pragma mark 其他方法
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section;
//設(shè)置分區(qū)標(biāo)題
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
//設(shè)置行高
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section;
//設(shè)置分區(qū)標(biāo)題視圖,和分區(qū)標(biāo)題的方法二選一即可
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section;
//設(shè)置分區(qū)標(biāo)題的高度
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
//cell的點(diǎn)擊事件實(shí)現(xiàn)方法