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

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

非常感谢,


当前回答

检查如何用StoryBoard实现标题:在StoryBoard中的表标题视图

还要注意,如果您没有实现

viewForHeaderInSection:(NSInteger)section

它不会浮动,这正是你想要的。

其他回答

UITableViewStyleGrouped的有趣之处在于tableView将样式添加到单元格中而不是添加到tableView中。

样式作为backgroundView添加到单元格中,作为一个名为UIGroupTableViewCellBackground的类,它根据单元格在section中的位置来处理绘制不同的背景。

所以一个非常简单的解决方案是使用UITableViewStyleGrouped,设置表格的backgroundColor为clearColor,并简单地替换cellForRow中单元格的backgroundView:

cell.backgroundView = [[[UIView alloc] initWithFrame:cell.bounds] autorelease];

虽然这可能不能解决您的问题,但当我想做类似的事情时,它确实解决了我的问题。我没有设置页眉,而是使用了上面部分的页脚。拯救我的是这个部分很小而且本质上是静态的,所以它不会滚动到视图底部以下。

你可以通过在tableview delegate类中实现viewForHeaderInSection方法轻松实现。这个方法期望一个UIView作为返回对象(这是你的头视图)。我在代码中也做了同样的事情

代码片段仅为第一部分显示粘头。其他的节头将与单元格一起浮动。

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {

    if section == 1 {
        tableView.contentInset = .zero
    }

}

func tableView(_ tableView: UITableView, didEndDisplayingHeaderView view: UIView, forSection section: Int) {
    if section == 0 {
        tableView.contentInset = .init(top: -tableView.sectionHeaderHeight, left: 0, bottom: 0, right: 0)
    }
}

这可以通过在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];
}

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