Skip to content

tableView常用方法总结

郑勇 edited this page Aug 25, 2016 · 8 revisions

###1.设置cell选择状态的界面 在tableview的delegate方法

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

里面写改变选中状态cell的界面

在tableview的delegate方法

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath

里面改变为非选中状态cell的界面


###2.设置tableview默认选中某一行

[self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionNone];
[self tableView:self.tableView didSelectRowAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0]];

第一行代码使tableView的第一行的选中背景显示出来但是没有1中的第一句代码的效果(第二句代码可以加上这种效果)


###3.设置cell的分割线左边顶到tableview最左边 初始化tableview的时候先写上这些代码

if ([_leftTableView respondsToSelector:@selector(setSeparatorInset:)]) {
            [_leftTableView setSeparatorInset:UIEdgeInsetsZero];
        }
if ([_leftTableView respondsToSelector:@selector(setLayoutMargins:)]) {
            [_leftTableView setLayoutMargins:UIEdgeInsetsZero];
        }

然后再在tableView的delegate方法中这样写

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

###4.取消 cell 的选中状态背景色 在初始化 cell 后设置 cell.selectionStyle = UITableViewCellSelectionStyleNone; 选中状态就没颜色了。


###5.Grouped 样式的 TableView 的 SectionHeader 和 SectionFodder 高度 Grouped 样式的 TableView 的 SectionHeader 和 SectionFodder 高度默认都是20,如果不想要这个高度,在 TableView 的代理方法

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section

中返回0是没用的,还是会有默认高度,应该返回一个很小的值,比如0.001。