? UITableView的數據源和代理:
數據源方法
必須要實現的數據源方法 ?(1 ,2 必須實現)
1. ?- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section:每組數據有多少行
2. ? - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath:
每一組的每一行顯示什么樣的cell
其他常用但不是必須要實現的數據源方法:(3, 4 ?不必須實現)
3.- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView;:
數組中返回右邊的索引顯示的內容
4.- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath;:提交編輯。只要實現了這個方法,就可以實現左滑出現按鈕。至于出現那些按鈕,在這個代理方法中傳入--- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath );數組中裝的是UITableViewRowAction對象
代理方法
沒有必須要實現的方法,代理主要是監聽事件和做一些附加的約束
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;:
返回對應cell的高度,適用于不等高的cell時,動態的設置每個cell的高度;
(注意:如果是等高的cell,可以設置tableView.rowHeight屬性,是每行等高;不設置,默認cell的高度44)
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;:
當選中了某一行的時候調用
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath;:
返回進入編輯模式之后,每一行的編輯模式類型(左邊的按鈕)
- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath ;:返回左滑是出現的按鈕,數組中裝的是UITableViewRowAction對象
注意點:
使用tableview的時候一定要注意性能,相同類型的cell要重用。
使用自動布局設置cell子控件的布局的時候:
使用xib或者storyBoard:
首先在interfaceBuilder中添加好約束;
再根據模型內容計算cell的高度。傳入模型之后,讓cell進行布局(調用[self layoutIfNeeded]方法)之后,系統會根據添加的約束計算出各個子空間的位置和尺寸,就可以根據內容得到行高了(減掉不需要顯示的內容的尺寸就好)。
使用純代碼:
在初始化的時候把所有的子控件添加上去。
在- (void)layoutSubviews方法中加上布局(注意不要重復添加約束,且要再調用[super layoutSubviews]方法之前添加)
再根據模型內容計算cell的高度。傳入模型之后,讓cell進行布局(調用[super layoutSubviewsIfNeeded]方法)之后,系統會根據添加的約束計算出各個子空間的位置和尺寸,就可以根據內容得到行高了(減掉不需要顯示的內容的尺寸就好)。
通過autoLayout使label根據最大寬度自動換行且自適應高度:
設置label的行數numOfLines為 0 ;
設置label的preferredMaxLayoutWidth(展示內容的最大寬度,即文字的最大寬度),這樣label才可以自動根據文字布局(根據最大寬度,自動布局高度),達到自動換行的目的。
注意:如果這個時候添加了label的寬度約束,就會發生約束沖突(不一定會報錯誤),因為preferredMaxLayoutWidth里面會結合label的字體等,計算出label的寬度
新的寫法(注冊cell)
NSString *ID = @"wine";
- (void)viewDidLoad {
[super viewDidLoad];
// 注冊某個重用標識 對應的 Cell類型
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:ID];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// 1.先去緩存池中查找可循環利用的cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
// 2.設置數據
cell.textLabel.text = [NSString stringWithFormat:@"%zd行的數據", indexPath.row];
return cell;
}