天天看點

iOS UITableView 讓cell分割線(Separator)從左邊0的位置開始

在做APP的個人中心或者其它頁面的時候會要求頁面cell的分割線是從左邊0開始的,但是系統預設是間隔了15像素的距離的,如下圖1-1

iOS UITableView 讓cell分割線(Separator)從左邊0的位置開始

圖1-1

可能大家都會說自定義cell就搞定了啊,沒錯,但是有沒有更加好一點的方法呢?畢竟自定義cell費時間啊(其實是懶),其實辦法還是有的,而且也簡單,在iOS7中可以通過設定

setSeparatorInset:

UIEdgeInsetsZero

,在iOS8改成

setLayoutMargins:

方法了,為了相容iOS7,是以要加個判斷,具體代碼在tableView頁面添加下面的方法即可:

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

- (void)viewDidLayoutSubviews
{
    if ([_tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [_tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([_tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [_tableView setLayoutMargins:UIEdgeInsetsZero];
    }
}           

複制

完成之後效果如圖1-2,是不是很省事?:

iOS UITableView 讓cell分割線(Separator)從左邊0的位置開始

圖1-2