iOS中UITableView分割线左侧顶齐

iOS 7开始UITableView的分割线不在从左侧边界开始了,而是默认空出了一段距离。

如果想要使用默认的分割线而且还要从左侧边界开始的话,有几种解决方式:

1、在tableView的代理方法中设置

- (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];
    }
    
    if([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]){
        [cell setPreservesSuperviewLayoutMargins:NO];
    }
}

2、既设置tableView代理,又设置tableView属性

首先在初始化tableView的时候,加上如下这两句:

    if ([_tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [_tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([_tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [_tableView setLayoutMargins:UIEdgeInsetsZero];
    }
然后在代理方法中这样设置:

- (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];
    }
}
上面这种做法也是可以的。

2、重写分割线

UITableView的分割线也是用UIView做的,具体可以看UITableView的层次结构,可以发现它其实是UITableViewCellSeparatorView,是cell的一个子视图。

<_UITableViewCellSeparatorView: 0x7f9f5a64cf80; frame = (0 59.5; 200 0.5); layer = <CALayer: 0x7f9f5a627a80>>

这是我打印的demo中一个小tableView中的系统默认分割线的信息,猜测是UIView的某个子类,所以我们自定义一个UIView高度设置为0.5,添加到cell上即可。


原文地址:https://www.cnblogs.com/wanghang/p/6298860.html