UITableView中每行數(shù)據(jù)都是一個UITableViewCell,在這個控件中為了顯示更多的信息,iOS已經(jīng)在其內部設置好了多個子控件以供開發(fā)者使用,如果系統(tǒng)樣式的cell不能滿足程序員需求是我們可以創(chuàng)建一個子類去自定義.我們查看UITableViewCell的聲明文件可以發(fā)現(xiàn)在內部有一個UIView控件,(contentView,作為其他元素的父控件).
數(shù)據(jù)源:由于iOS是遵循MVC模式設計的,很多操作都是通過代理和外界溝通的,但對于數(shù)據(jù)源控件除了代理還有一個數(shù)據(jù)源屬性,通過它和外界進行數(shù)據(jù)交互。 對于UITableView設置完dataSource后需要實現(xiàn)UITableViewDataSource協(xié)議,在這個協(xié)議中定義了多種 數(shù)據(jù)操作方法. 一般通過創(chuàng)建一個模型(懶加載)的方式去加載數(shù)據(jù).
數(shù)據(jù)源方法:
#pragma mark 返回組數(shù)
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;(默認1)
}
#pragma mark 返回每組行數(shù)
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return group1.contacts.count;
}
#pragma mark返回每行的單元格
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//1.創(chuàng)建cell
//2.設置數(shù)據(jù)
//3.返回cell
return cell;
}
#pragma mark 返回每組頭標題名稱
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
return group.name;
}
#pragma mark 返回每組尾部說明
-(NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section{
return group.detail;
}
代理:
當發(fā)現(xiàn)單元格高度、分組標題高度以及尾部說明的高度都需要調整,此時就需要使用代理方法。UITableView代理方法有很多,例如監(jiān)聽單元格顯示周期、監(jiān)聽單元格選擇編輯操作、設置是否高亮顯示單元格、設置行高等。
1.設置行高
#pragma mark - 代理方法
#pragma mark 設置分組標題內容高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
if(section==0){
return 50;
}
return 40;
}
#pragma mark 設置每行高度(每行高度可以不一樣)
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 45;
}
#pragma mark 設置尾部說明內容高度
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
return 40;
}
2.監(jiān)聽用戶點擊方法:
#pragma mark 點擊行
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
_selectedIndexPath=indexPath;
}
#pragma mark 窗口的代理方法,用戶保存數(shù)據(jù)
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
}
}
#pragma mark 重寫狀態(tài)樣式方法
-(UIStatusBarStyle)preferredStatusBarStyle{
return UIStatusBarStyleLightContent;
}
UITableViewCell
1.自帶的UITableViewCell
UITableViewCell是構建一個UITableView的基礎,在UITableViewCell內部有一個UIView控件作為其他內容的容器,它上面有一個UIImageView和兩個UILabel,通過UITableViewCellStyle屬性可以對其樣式進行控制。
2.自定義UITableViewCell
定義一個TableViewCell實現(xiàn)UITableViewCell,一般實現(xiàn)自定義UITableViewCell需要分為兩步:第一初始化控件;第二設置數(shù)據(jù),重新設置控件frame。原因就是自定義Cell一般無法固定高度,很多時候高度需要隨著內容改變。此外由于在單元格內部是無法控制單元格高度的,因此一般會定義一個高度屬性用于在UITableView的代理事件中設置每個單元格高度。