iOS开发代码段iOS技术专题iOS 开发

UITableViewCell分隔线缺失解决方法

2016-04-10  本文已影响349人  其字德安
引发问题:在使用tableView的时候发现, cell下面的分隔线居然不是全屏的!

每个cell前面都有一段差距, 这对于强迫症的人来说,无法忍受...

01.png

方法一: 在cell下面自定义一条分隔线, 替代系统原有的;

实现步骤:

#import "ViewController.h"
#import "ABCell.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // 取消系统的分隔线
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}

#import "ABCell.h"

@implementation ABCell

- (void)layoutSubviews {

    [super layoutSubviews];

    // 初始化数据
    CGFloat w = self.frame.size.width;
    CGFloat h = 1;
    CGFloat x = 0;
    CGFloat y = self.frame.size.height - 1;
    // 添加自定义分隔线
    UIView *sepLine = [[UIView alloc] init];

    sepLine.frame = CGRectMake(x, y, w, h);

    // 设置背景色
    sepLine.backgroundColor = [UIColor colorWithRed:200/255.0 green:199/255.0  blue:204/255.0  alpha:1];


    [self.contentView addSubview:sepLine];
}

// 注: 这里颜色可以自己设, 为了严谨,我用取色计取值, 但可能有误差
@end

方法二: tableView控制器中添加下面方法

- (void)viewDidLayoutSubviews {

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

        self.tableView.layoutMargins = UIEdgeInsetsZero;
    }
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {

        self.tableView.separatorInset = UIEdgeInsetsZero;
    }
}

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

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

        cell.layoutMargins = UIEdgeInsetsZero;
    }

    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        cell.separatorInset = UIEdgeInsetsZero;
    }
}

方法三: 通用的方法 推荐第三种方法

三步曲:

代码实现:


#import "ViewController.h"
#import "ABCell.h"

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // 1.0 取消系统的分隔线
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    // 2.0 设置背景颜色
    self.tableView.backgroundColor = [UIColor grayColor];
}

#import "ABCell.h"
@implementation ABCell

// 重写系统方法
- (void)setFrame:(CGRect)frame {

    // 设置分隔线的高度
    frame.size.height -= 1;

    // 务必调用系统的方法
    [super setFrame:frame];
}

解析:

三种方法补全后效果图:

03.png

最后: 没写全, 或者写错的地方; 请帮忙告诉我,thanks.

上一篇 下一篇

猜你喜欢

热点阅读