問題描述
使用UITableViewDelegate
代理方法來設置header
或footer
時要注意了。
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
return [UIView new];
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
return 1;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
return [UIView new];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
return 1;
}
UITableView
在UI
佈局中使用的場景很多,比如下圖:
使用場景:讓UITableView
的contentSize
的高度和父控件的高度一致。
- 沒有使用分組(即沒有設置
header
或footer
),這個時候通過獲取UITableView
的contentSize
的高度來設置父控件的高度,顯示出來的效果是正常的; - ⚠️⚠️使用了分組(即設置了
header
或footer
),這個時候通過獲取UITableView
的contentSize
的高度來設置父控件的高度,顯示出來的效果是不正常的;
剖析
舉例:當我們使用UITableViewDelegate
代理方法來設置footer
時,先調用
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section;
,
然後調用
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section;
,
但是當我們設置footer
的高度爲0
或CGFLOAT_MIN
時,執行完
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section;
,
就不會調用
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section;
,
所以這個時候通過獲取UITableView
的contentSize
的高度來設置父控件的高度,顯示出來的效果是不正常了。
解決方案
當我們使用UITableViewDelegate
代理方法來設置header
或footer
時,儘量不要給header
或footer
的高度設爲0
或CGFLOAT_MIN
,應該設置一個很小的高度,eg
:1
,2...
。