去掉UITableView多余的空白行分割线

一、问题描述

在学习和开发中经常会遇到下面的问题,UITableView的UITableViewCell很少或者没有时,但UITableView有很多的空白行分割线。如下图:

 

如何去掉UITableView多余的空白行分割线?

二、问题分析

方法一:隐藏UITableViewCell自带的分割线,然后自定义分割线到UITableViewCell。自定义分割线的方法有很多种,可以自行查找。

方法二:很简单,修改tableFooterView。创建frame为CGRectZero的UIView,赋值给tableFooterView

 

二、问题解决

1.自定义分割线

列举自定义分割线的其中一种方法。

步骤一:全局设置UITableViewCell系统自带分割线“隐藏”,这个“隐藏”只是把分割线颜色设置为透明。这样做目的是为了保持自定义分割线frame和系统自带的分割线一样。如果不想一样,可以真正隐藏。

1 -(void)viewDidLoad
2 {
3     //设置分割线的风格
4     self.tableViewCategory.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
5     self.tableViewCategory.separatorColor = [UIColor clearColor];
6     self.tableViewList.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
7     self.tableViewList.separatorColor = [UIColor clearColor];
8 }

 

步骤二:在UITableViewCell

 1 // 自绘分割线
 2 - (void)drawRect:(CGRect)rect
 3 {
 4     //获取cell系统自带的分割线,获取分割线对象目的是为了保持自定义分割线frame和系统自带的分割线一样。如果不想一样,可以忽略。
 5     UIView *separatorView = [self valueForKey:@"_separatorView"];
 6     NSLog(@"%@",NSStringFromCGRect(separatorView.frame));
 7     NSLog(@"%@",NSStringFromCGRect(rect));
 8     [super drawRect:rect];
 9     CGContextRef context = UIGraphicsGetCurrentContext();
10     CGContextSetStrokeColorWithColor(context, [UIColor colorWithRed:232/255.0 green:232/255.0 blue:232/255.0 alpha:1].CGColor);
11     //CGContextStrokeRect(context, CGRectMake(0, rect.size.height - 1, rect.size.width, 1));
12     CGContextStrokeRect(context, separatorView.frame);
13 }

 效果:

 

2.修改tableFooterView

1  self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];

效果:

 

posted @ 2016-07-08 19:42  阿水zev  阅读(7765)  评论(0编辑  收藏  举报