UITabViewCell自定义分割线

来源:互联网 发布:省市区编码 json数据 编辑:程序博客网 时间:2024/04/29 15:39

2016年8月7日

UITabViewCell自定义分割线

在UITableView的使用中,通常需要设置分割线。但是分割线会经常短一截的情况,针对这个情况,有三种方式可以解决。

1 自定义UIView充当分割线

实现原理,自定义CMTableViewCell继承自UITableViewCell,使用懒加载创建高度为1的UIView,重写layoutSubViews布局UIView的位置。

自定义cell的.m文件

@interface CMTableViewCell ()@property(nonatomic,weak) UIView *separatorView;@end@implementation CMTableViewCell//使用懒加载创建分割线view,保证一个cell只有一条-(UIView *)separatorView{    if (_separatorView == nil) {        UIView *separatorView = [[UIView alloc]init];        self.separatorView = separatorView;        separatorView.backgroundColor = [UIColor redColor];        [self addSubview:separatorView];    }    return _separatorView;}//重写layoutSubViews方法,设置位置及尺寸-(void)layoutSubviews{    [super layoutSubviews];    self.separatorView.frame = CGRectMake(0, self.bounds.size.height-1,     self.bounds.size.width, 1);}

2 修改系统属性–主要是系统适配

iOS6的时候cell的分割线是屏幕宽的,但是现在不是了,向右缩进了一些距离

iOS7的时候,苹果对tableView增加了一个叫separatorInset的东西,会改变分割线的边距

iOS8,内部增加一些自动布局的东西,我们可以在storyboard添加约束的时候可以感受到,每次添加约束的时候,都会勾掉一个叫constraint to margins的选项。–所以这个我们需要注意

所以,我们可以通过修改这些属性得到答案

- (void)viewDidLoad {    [super viewDidLoad];    // Do any additional setup after loading the view, typically from a nib.    //都是针对tableView来看    //1 去除掉自动布局添加的边距    self.tableView.layoutMargins = UIEdgeInsetsMake(0, 0, 0, 0);    //2 去掉iOS7的separatorInset边距    self.tableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);}-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{    return 20;}-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{    static NSString *ID = @"cell";    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];    if (cell == nil) {        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];    }    cell.textLabel.text = @"haha";    //去掉cell的自动布局添加的边距    cell.layoutMargins = UIEdgeInsetsMake(0, 0, 0, 0);    return cell;}

3 巧妙利用TableView的背景作为分割线—万能方式

这个方式的巧妙之处在于,保持每个cell的位置不变,也就是坐标仍然位置系统自动计算好的,调整cell的高度,让后边的tableView露出来,利用tableView的背景色作为分割线。

关键点:tableView的cell,在初始化的时候frame就已经全部计算好了,当cell即将显示的时候会调用setFrame方法来给cell赋值,所以,我们就可以重写setFrame方法拦截,修改frame里面的height,达到目的。

CMTableViewCell.m文件

- (void)viewDidLoad {[super viewDidLoad];    //1 禁用系统自带的分割线    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;    //2 设置tableView的背景色跟系统自带的背景色一致 198 198 203    self.tableView.backgroundColor = [UIColor colorWithRed:198/255.0 green:198/255.0 blue:203/255.0 alpha:1];    //3 重写cell的setFrame的方法-在自定义cell中设置}

CMTableCell.m文件

//3 重写setFrame方法-(void)setFrame:(CGRect)frame{    //只修改高度    frame.size.height-=1;    //调用系统方法设置    [super setFrame:frame];}
0 0
原创粉丝点击