天天看點

自定義cell分割線

從iOS7開始tableView的系統自帶的cell 分割線是不會占滿整個寬度的 總是向右空出15個寬度,最近在寫項目,遇到這個問題,特此在這裡給出解決辦法

1.UITableView中将分割線樣式改為None

2.自定義UITableViewCell中複寫- (void)drawRect: (CGRect)rect方法

- (void)drawRect:(CGRect)rect
{
     CGContextRef context = UIGraphicsGetCurrentContext();
     CGContextSetFillColorWithColor(context, [UIColor clearColor].CGColor);
     CGContextFillRect(context, rect);
//上分割線,
    CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
    CGContextStrokeRect(context, CGRectMake(, , rect.size.width, ));

//下分割線
    CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
   CGContextStrokeRect(context, CGRectMake(, rect.size.height, rect.size.width, ));
}
           

這樣就解決了cell分割線問題了

最近發現了一個更好的解決辦法不需要重新自定義之前的那種方法對iOS7和8的适應不是很好,會出現問題。

最新的解決辦法如下

在viewDidLoad中加上

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

[self.tableView setSeparatorInset:UIEdgeInsetsZero];

}

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

[self.tableView setLayoutMargins:UIEdgeInsetsZero];

}
           

然後再代理方法willDisplayCell中加上

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([cell    respondsToSelector:@selector(setSeparatorInset:)]) {
[cell setSeparatorInset:UIEdgeInsetsZero];
}
if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
[cell setLayoutMargins:UIEdgeInsetsZero];
}
}
           

OK了