项目开发技巧iOS开发指南iOS实用编程技巧

iOS系统中UITableViewCell分割线设置和分割线偏移

2015-11-02  本文已影响2920人  51bitquant

iOS系统中UITableViewCell分割线设置和分割线偏移处理

iOS项目中大量使用到UITableView,为了美观可能需要对UITableViewCell的分割线进行特别的处理。如果UITableViewCell简单的话,为了快速开发,直接使用系统的UITableViewCell,然后直接设置tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine既可以,这在ios7以前是没有问题的,但是iOS8以后,直接设置cell.seperatorInsets 已经不生效了。原因是iOS8以后系统给UIView增加了layoutMargins,在UIView 中可以看到如下定义:

    @property (nonatomic) UIEdgeInsets layoutMargins NS_AVAILABLE_IOS(8_0);

如果想使用系统的分割线,可以通过下面方法设置:

1.在viewDidLoad方法中添加下面代码:

    
    /**
     *  UITableView
     */
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
  1. 实现UITableView中的tableView:willDisplayCell:forRowAtIndexPath:代理方法,代码如下:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath

{
    // 设置需要的偏移量,这个UIEdgeInsets左右偏移量不要太大,不然会titleLabel也会便宜的。
    UIEdgeInsets inset = UIEdgeInsetsMake(0, 10, 0, 0);
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) { // iOS8的方法
        if (indexPath.row == self.labelArray.count-1) {
            [cell setLayoutMargins:UIEdgeInsetsZero];
        } else {
            // 设置边界为0,默认是{8,8,8,8}
            [cell setLayoutMargins:inset];
        }
        
    }
    
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        
        if (indexPath.row == self.labelArray.count-1) {
            [cell setSeparatorInset:UIEdgeInsetsZero];
        } else {
            [cell setSeparatorInset:inset];
        }
    }
}

效果如下:

demo.png

如果你不想使用系统的效果,你可以在UITableCell中自己绘制分割线,但是处理合理的话,利用系统的效果也不错,至少相对简单些。

上一篇 下一篇

猜你喜欢

热点阅读