iOS中UITableView使用的常见问题总结

2020-01-18 21:46:21刘景俊

1、如何设置headerView以及其高度


tableView.tableHeaderView = myHeaderView
 
let height = headerView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
var frame = headerView.frame
frame.size.height = height
headerView.frame = frame

2、去掉多余cell的分割线


self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];

3、如何设置section数、行数


extension MyViewController: UITableViewDataSource {
 
 // section数
 func numberOfSections(in: UITableView) -> Int {
 }
 
 // row数
 public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
 }
 
 // 在section和row下,cell
 public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
 }
 
}

4、iOS 8+自动计算行高、section高度


tableView.estimatedRowHeight = 80
tableView.rowHeight = UITableViewAutomaticDimension

实际上,sectionHeader高度也可以自动算高


tv.estimatedSectionHeaderHeight = 20
tv.sectionHeaderHeight = UITableViewAutomaticDimension

当然sectionFooter也可以,不再赘述

5、禁用tableview自带的分割线


tv.separatorStyle = .none

6、设置sectionHeader和sectionFooter,以及他们的高度

view


extension MyViewController: UITableViewDelegate {
 func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
 
 }
 
 func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
 
 }
}

高度


extension TTEntranceExamReportViewController: UITableViewDelegate {
 func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
 }
 
 func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
 }
}

7、点击cell有阴影,抬起时候阴影消失


func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
 tableView.deselectRow(at: indexPath, animated: no)
 // other code
}

8、iPad的UITableViewCell自动缩进的问题


if (IS_IPAD && [_tableView respondsToSelector:@selector(setCellLayoutMarginsFollowReadableWidth:)]) {
 _tableView.cellLayoutMarginsFollowReadableWidth = NO;
}

Swift版:


if IS_IPAD, #available(iOS 9.0, *) {
 tableView.cellLayoutMarginsFollowReadableWidth = false
}

9、设定UITableviewCell按下的点击效果


cell.selectedBackgroundView = [[PureColorView alloc] initWithColor:[UIColor redColor]];