设置UITableView分割线左边间距

版权声明:未经本人允许,禁止转载.

iOS 7之后,tableView的分割线左边距默认设置为15,如图


设置UITableView分割线左边间距_第1张图片
左间距15的分割线.png

iOS 7 添加属性separatorInset,设置为UIEdgeInsetsZero即可左对齐
iOS 8之后,由于view添加属性layoutMargins,所以需要两个属性都设置为 UIEdgeInsetsZero

1.代码设置

  1. 首先在- viewDidLayoutSubviews方法里设置tableView的separatorInset和layoutMargins
    //OC
    - (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    //设置separatorInset(iOS7之后)
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
    [self.tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    //设置layoutMargins(iOS8之后)
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
    [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    }
    //Swift
    override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    if self.tableView.respondsToSelector(Selector("setSeparatorInset:")) {
    self.tableView.separatorInset = UIEdgeInsetsZero
    }
    if self.tableView.respondsToSelector(Selector("setLayoutMargins:")) {
    self.tableView.layoutMargins = UIEdgeInsetsZero
    }
    }
  2. 在- tableView:willDisplayCell:forRowAtIndexPath:方法(cell将要出现)里设置cell的separatorInset和layoutMargins
    //OC
    - (void)tableView:(UITableView *)tableView willDisplayCell:(nonnull UITableViewCell *)cell forRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    //设置separatorInset(iOS7之后)
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
    [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    //设置layoutMargins(iOS8之后)
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
    [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    }
    //Swift
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    if cell.respondsToSelector(Selector("setSeparatorInset:")) {
    cell.separatorInset = UIEdgeInsetsZero
    }
    if cell.respondsToSelector(Selector("setLayoutMargins:")) {
    cell.layoutMargins = UIEdgeInsetsZero
    }
    }

2.Xib/Storyboard设置

需要同时设置tableView和cell的separatorInset和layoutMargins.(针对tableView和tableViewController的xib和storyboard不同情况,选择性设置即可,最多4个都设置)

  1. 首先设置TableView的separatorInset,如图


    设置UITableView分割线左边间距_第2张图片
    设置TableView的SeparatorInset.png

    设置TableView的layoutMargins,如图


    设置UITableView分割线左边间距_第3张图片
    设置TableView的LayoutMargins.png
  2. 设置TableViewCell的separatorInset,如图


    设置UITableView分割线左边间距_第4张图片
    设置Cell的SeparatorInset.png

    设置TableViewCell的layoutMargins,如图


    设置UITableView分割线左边间距_第5张图片
    设置Cell的LayoutMargins.png

你可能感兴趣的:(设置UITableView分割线左边间距)