UITableView指定分割线 并且设置颜色

UITableView的分割线(separator)是私有类,应该是无法获取的。

不过你可以通过tableView的属性修改它:

1
2
3
4
5
6
7
8
9
UITableView * tableView = [[UITableView alloc] initWithFrame:CGRectMake(20, 20, 400, 300) style:UITableViewStylePlain];
     tableView.separatorColor = [UIColor redColor];
     tableView.separatorInset = UIEdgeInsetsMake(0,80, 0, 80);         // 设置端距,这里表示separator离左边和右边均80像素
     tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
     tableView.dataSource = self;

如此设置后的tableView是这样的:(左右空出了80像素)

如果你想设置单个分割线的颜色,那就自己画分割线吧。你可以用coreGraphics,也可以用UIView,这里用UIView来画:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
UITableView * tableView = [[UITableView alloc] initWithFrame:CGRectMake(20, 20, 400, 300) style:UITableViewStylePlain];
     
     tableView.separatorStyle = UITableViewCellSeparatorStyleNone;    // 这样就不会显示自带的分割线
     tableView.dataSource = self;
     
     for  ( int  i = 0; i < 8; i++) {
         
         UIView * separator = [[UIView alloc] initWithFrame:CGRectMake(10, (i+1) * 40  /* i乘以高度*/ , 380, 1)];
         
         separator.backgroundColor = [UIColor colorWithRed:0.03 * i green:0.05*i blue:0.1*i alpha:1];
         
         [tableView addSubview:separator];
         
     }
     
     [self addSubview:tableView];

效果:

滚动正常

当然,为了和谐,你应该把自定义的separator的间隔和cell的高度设为一致。

追问:
你好,还想问一句,当点击cell的时候如何让当前cell下的分割线变色呢,然后点击别的cell的时候,在恢复原状!

追答:
现在实际上我们用的很多的tableview都不会用它自带的分割线,通常是用一个UITableViewCell的子类来画分割线,分割线直接画在cell上面。
代码刚刚我实现了,但是继续回答会超过度娘规定的字符上限- -。
我给你说一下思路:
首先需要一个UITableViewCell的子类:比如叫TableViewCell
在里面有一个属性:
@property (nonatomic,strong) UIView * separator;
在它的initwithStyle...方法里面在底部画分割线:UIView * separator = [[UIView alloc] initWithFrame:CGRectMake(10, self.frame.size.height - 1, self.frame.size.width - 10, 1)];self.separator = separator;[self addSubview:_separator];在datasource方法,返回cell的方法里面用我们的TableViewCell初始化cell,然后赋值颜色cell.separator.backgroundColor = [UIColor blueColor];
点击cell的Delegate方法里面:TableViewCell * cell = (TableViewCell *)[tableView cellForRowAtIndexPath:indexPath];cell.separator.backgroundColor = [UIColor grayColor];