1.UITableView的概念
- UITableView繼承于UIScrollView,可滾動
- UITableView的每一條數(shù)據(jù)對應(yīng)的單元格叫做Cell,是UITableViewCell的一個對象,繼承于UIView
- UITableView可以分區(qū)顯示,每一個分區(qū)稱為section,每一行稱為row,編號都是從0開始
- 系統(tǒng)提供了一個專門的類來整合section和row,叫做NSIndexPath
2.UITableView的基本使用
系統(tǒng)提供了一個類UITableViewController,用于方便管理UITableViewController
UITableView顯示的相關(guān)屬性
self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;// 分割線樣式
self.tableView.separatorColor = [UIColor redColor];// 分割線顏色
self.tableView.tableHeaderView 置頂視圖
self.tableView.tableFootView 置底視圖
3.UITableView顯示數(shù)據(jù)
遵守UITableViewDelegate與UITableViewDataSource
- dataSource,顯示數(shù)據(jù)相關(guān)代理
- detegate,視圖操作相關(guān)代理
// 設(shè)置dataSource代理
tableView.delegate = self;
// 設(shè)置delegate代理
tableView.dataSource = self;
然而TableViewController中已經(jīng)自帶協(xié)議并且已經(jīng)設(shè)置好代理,所以不用重復(fù)以上代碼
必須實(shí)現(xiàn)的兩個協(xié)議方法
- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section;
- (UITableViewCell )tableView:(UITableView)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
3.UITableViewCell
首先要注冊Cell
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"reuse"];// 注冊UITableViewCell
然后實(shí)現(xiàn)方法
- (UITableViewCell *)tableView:(UITableView *)tableViewcellForRowAtIndexPath:(NSIndexPath *)indexPath{
// 從重用池中獲取cell
UITableViewCell *cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:@"reuse"] autorelease];
cell.textLabel.text = @"標(biāo)題";
return cell;
}
4.重用機(jī)制
解決問題:如果tableView要顯示超過100條數(shù)據(jù),需要多少個cell?內(nèi)存畢竟超過每個App的規(guī)定,造成閃退
重用cell的流程
1.當(dāng)一個cell被滑出屏幕,這個cell會被程序放到相應(yīng)的重用池中
2.當(dāng)tableView需要顯示一個cell,會先去重用池中嘗試獲取一個cell
3.如果重用池沒有cell,就會創(chuàng)建一個cell
4.取得cell之后會重新賦值進(jìn)行使用
5.UITableView常用方法
// 返回分區(qū)頭部標(biāo)題
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return @"頭部標(biāo)題";
}
// 返回底部標(biāo)題
- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
return @"底部標(biāo)題";
}
// 返回UITableView右側(cè)索引目錄
- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView {
return @[@"1"];
}
// 告訴delegate選中了一個cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"選中");
}
// 每一個分區(qū)的頂部高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
return 10;
}
// 每一個分區(qū)的底部高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
return 10;
}
// 每一個分區(qū)的頂部自定義視圖
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
}
// 每一個分區(qū)的底部自定義視圖
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
}