iOS UITableView分割线颜色,长度自定义

本文介绍如何在iOS应用开发中自定义表格视图的分割线样式及长度,通过调整`separatorInset`和`layoutMargins`实现美观且灵活的分割线效果。

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

表是我们开发中经常使用的一个控件,而我们在开发中万恶的UI总会给我们指出各种各样无语的问题。比如要在单元格的下面添加一条2px的线,美名曰好看。用系统自带的效果人家还不同意,美名曰线要到头。好吧,给大家一个方法,让分割线自由长度随你心意。当然,我看到网上已经有这方面的回答了。但是我还是自己总结一下,纠结了自己那么久的问题,记录一下。

首先,demo的地址链接:https://github.com/sunyunfei/DividerDemo.git

开始代码部分,基本的创建就不说了,直接看分割线设置部分:

/**

 *  分割线设置代码

 */

-(void)viewDidLayoutSubviews

{

    UIEdgeInsets edgeInset = UIEdgeInsetsMake(0, 0, 0, 0);

    

    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {

        [self.tableView setSeparatorInset:edgeInset];

    }

    

    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {

        [self.tableView setLayoutMargins:edgeInset];

    }

}

/**

 *   行将要显示的时候调用

 *

 *  @param tableView <#tableView description#>

 *  @param cell      <#cell description#>

 *  @param indexPath <#indexPath description#>

 */

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath

{

    UIEdgeInsets edgeInset = UIEdgeInsetsMake(0, 0, 0, 0);

    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {

        [cell setSeparatorInset:edgeInset];

    }

    

    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {

        [cell setLayoutMargins:edgeInset];

    }

}



这是核心代码,edgeInset这一个属性是表的,上网查了下,这个在iOS7之前是没有的,有的人说直接用cell.separatorInset =UIEdgeInsetsZero;这一句也可以让分割线宽度占满,但是我自己试验了一下没有用。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值