我使用UITableView来布局内容“页面”。我使用表视图的标题来布局某些图像等,我更喜欢它,如果他们没有浮动,但保持静态,因为他们做的时候,风格设置为UITableViewStyleGrouped。

除了使用UITableViewStyleGrouped,有办法做到这一点吗?我想避免使用分组,因为它增加了我所有的单元格的边缘,并要求为每个单元格禁用背景视图。我想完全控制我的布局。理想情况下,它们应该是“UITableViewStyleBareBones”,但我在文档中没有看到这个选项…

非常感谢,


当前回答

裁判:https://stackoverflow.com/a/26306212

let tableView = UITableView(frame: .zero, style: .grouped)

PLUSE

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    if section == 0 {
        return 40
    }else{
        tableView.sectionHeaderHeight = 0
    }

    return 0
}

这有助于使用标题空间

其他回答

您应该能够通过使用自定义单元格来处理标题行来伪造这一点。然后,这些单元格将像表视图中的任何其他单元格一样滚动。

您只需要在cellForRowAtIndexPath中添加一些逻辑,以便在单元格是标题行时返回正确的单元格类型。

你可能不得不自己管理你的部分,也就是说,把所有的东西都放在一个部分,并伪造标题。(你也可以尝试为头视图返回一个隐藏视图,但我不知道这是否会工作)

一个棘手的方法是为标题添加一个空部分。因为section没有单元格,所以它根本不会浮动。

这可以通过在UITableViewController的viewDidLoad方法中手动分配头视图来实现,而不是使用委托的viewForHeaderInSection和hightforheaderinsection。例如,在UITableViewController的子类中,你可以这样做:

- (void)viewDidLoad {
    [super viewDidLoad];

    UILabel *headerView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
    [headerView setBackgroundColor:[UIColor magentaColor]];
    [headerView setTextAlignment:NSTextAlignmentCenter];
    [headerView setText:@"Hello World"];
    [[self tableView] setTableHeaderView:headerView];
}

当用户滚动时,头视图将消失。我不知道为什么这样工作,但它似乎达到了你想要做的。

@samvermette的解决方案的变体:

/// Allows for disabling scrolling headers in plain-styled tableviews
extension UITableView {

    static let shouldScrollSectionHeadersDummyViewHeight = CGFloat(40)

    var shouldScrollSectionHeaders: Bool {
        set {
            if newValue {
                tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: bounds.size.width, height: UITableView.shouldScrollSectionHeadersDummyViewHeight))
                contentInset = UIEdgeInsets(top: -UITableView.shouldScrollSectionHeadersDummyViewHeight, left: 0, bottom: 0, right: 0)
            } else {
                tableHeaderView = nil
                contentInset = .zero
            }
        }

        get {
            return tableHeaderView != nil && contentInset.top == UITableView.shouldScrollSectionHeadersDummyViewHeight
        }
    }

}

要完全删除浮动section头部分,你可以这样做:

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return [[UIView alloc] init];
}

返回nil无效。

要禁用浮动,但仍然显示节头,您可以提供一个具有自己行为的自定义视图。