iOS 修改UITableView separator

这篇博客介绍了如何在iOS中修改UITableView的分隔线样式和内边距。通过调整UITableView的separatorStyle属性可以改变分隔线类型,使用separatorColor设置颜色,而iOS 8.0后可用separatorInset控制显示效果。当修改Separator Inset不起作用时,提供了两种解决办法:方法一是通过代码动态设置;方法二是利用cell的布局来调整。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

separator style

UITableView 中的 separator 有三种类型:

typedef NS_ENUM(NSInteger, UITableViewCellSeparatorStyle) {
    UITableViewCellSeparatorStyleNone, // 没有分割线
    UITableViewCellSeparatorStyleSingleLine, // 单线,默认
    UITableViewCellSeparatorStyleSingleLineEtched   // 内嵌线,只有在 UITableView 为 group 类型时才起作用
}

通过修改 UITableView 的 separatorStyle 属性修改 separator 的类型,通过修改 separatorColor 属性修改 separator 的颜色,通过修改 separatorEffect( iOS 8.0 之后) 属性修改 separator 的显示特效。

separator inset

修改 separator 到边缘距离的时候,只需要修改 UITableView 的 separatorInset 属性就可以了,例如,当使用 xib 或 storyBoard 定制 cell 的时候,修改 tableview 的 Separator Inset 为 Custom,然后修改左右边距。但是最近突然发现这样完全不起作用了,即使手动修改 separatorInsetUIEdgeInsetsZero 也不起作用,具体什么原因没有细究,然后通过万能的百度,找到了解决方法:

方法一:

- (void)viewDidLoad {
    [super viewDidLoad];
   ...
   ...
   ...
#pragma mark - a 调整view边距
    // 1.调整(iOS7以上)表格分隔线边距
    if ([self.MyTableView respondsToSelector:@selector(setSeparatorInset:)]) {
        self.MyTableView.separatorInset = UIEdgeInsetsZero;
    }
    // 2.调整(iOS8以上)view边距(或者在cell中设置preservesSuperviewLayoutMargins,二者等效)
    if ([self.MyTableView respondsToSelector:@selector(setLayoutMargins:)]) {
        self.MyTableView.layoutMargins = UIEdgeInsetsZero;
    }

}

#pragma mark - b 调整view边距
//然后在willDisplayCell方法中加入如下代码:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
#pragma mark - b
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

方法二:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
...
...
...
#pragma mark - a 调整view边距
    //1.调整(iOS8以上)tableView边距(与上面第2步等效,二选一即可)
    if ([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) {
        cell.preservesSuperviewLayoutMargins = NO;
    }
    //2.调整(iOS8以上)view边距
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    return cell;
}

#pragma mark - b 调整view边距
//然后在willDisplayCell方法中加入如下代码:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
#pragma mark - b
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值