引发问题:在使用tableView的时候发现, cell下面的分隔线居然不是全屏的!
每个cell前面都有一段差距, 这对于强迫症的人来说,无法忍受...
01.png
方法一: 在cell下面自定义一条分隔线, 替代系统原有的;
实现步骤
:
- 取消系统的分隔线
- 自定义cell, 在
layOutsubviews
添加自定义分隔线
#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控制器中添加下面方法
-
该方法有弊端
: 在iOS7.0系统及以下会报错;因为layoutMargins
属性是8.0 才有的
- (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;
}
}
方法三: 通用的方法 推荐第三种方法
三步曲:
- 取消系统的分隔线
- 设置tableView的背景颜色
- 自定义cell, 重写系统的
setFrame:
方法
代码实现:
#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];
}
解析:
当系统自动计算好cell的尺寸后, 会调用该方法给cell真正设置
frame
我们这时候可以截取frame, 把cell的高度减1; 故显示后会露出高度为1(tableView的)背景颜色 (充当分隔线)
重点是必须再次调用
[super setFrame:frame]
;
三种方法补全后效果图:
03.png
最后: 没写全, 或者写错的地方; 请帮忙告诉我,thanks.