如何移除UITableView分区头部的分割线

11

我想要移除UITableView的分区头部分隔线(或将它们设置为clearColor)。设置tableView.separatorStyle = .none并不起作用。我也尝试了来自这里的解决方案,但是它们都没有真正对我起作用(也许是因为回答比较旧)。我仍然会在分区头部下面看到这个微小的分隔线。

我在Storyboard中创建了UITableView并添加了一个UITableViewCell。然后我将其设置为一个分区头,如下所示:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let cell = tableView.dequeueReusableCell(withIdentifier: "headerTableViewCell")
        return cell
    }

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 1 {
            return 49
        }
        return 0
    }

1
为什么你在 viewForHeaderInSection 中添加了 cell? - Nitin Gohel
4个回答

12

不知道为什么您在 viewForHeaderInSection 方法中返回了 UITableViewCell,因此可能会显示该 UITableViewCell 的分割线。尝试返回单元格的 contentView 而不是从 viewForHeaderInSection 方法返回整个单元格。

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let cell = tableView.dequeueReusableCell(withIdentifier: "headerTableViewCell")
    return cell.contentView
}

1

试试这个:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let headerView = UIView()
    headerView.backgroundColor = UIColor.clear
    return headerView
}

0
我是通过以下方式解决的:
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }

实际上这是一个很好的方法。虽然你可以只写return 0 - Jin Wang
2
在某些情况下,0会被忽略(分组视图)。您应该返回CGFloat.leastNormalMagnitude - inexcitus

0

原来重写layoutSubviews会移除所有单元格的分隔线,包括节相关和单元格相关的。

@interface MyCustomCell : UITableViewCell

@end    

@implementation MyCustomCell

- (void)layoutSubviews {
    // don't call [super layoutSubviews]
    // can be left empty
    // does not harm other UI elements inside the contentView
}

@end

在多单元格的部分中,您可能只想删除与“区域”相关的分隔符(即第一个单元格顶部和最后一个单元格底部的分隔符),并保留缩进、单元格间的分隔符。
- (void)layoutSubviews {
    [super layoutSubviews];

    for (UIView *view in self.subviews) {
        if ([view isEqual:self.contentView]) continue;

        view.hidden = view.bounds.size.width == self.bounds.size.width;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接