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

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

非常感谢,


当前回答

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

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

其他回答

警告:这个解决方案实现了一个保留的API方法。这可能会阻止苹果批准该应用程序在AppStore上发布。

我已经在我的博客中描述了使节头浮动的私有方法

基本上,你只需要子类化UITableView并在它的两个方法中返回NO:

- (BOOL)allowsHeaderViewsToFloat;
- (BOOL)allowsFooterViewsToFloat;

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

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

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

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

**Swift 5.3 |编程**

private func buildTableView() -> UITableView {
    let tableView = UITableView()
    tableView.translatesAutoresizingMaskIntoConstraints = false
    tableView.rowHeight = UITableView.automaticDimension
    tableView.showsVerticalScrollIndicator = false
    tableView.separatorStyle = .none
    let dummyViewHeight: CGFloat = 80
    tableView.tableFooterView = UIView(
        frame: CGRect(x: .zero,
                      y: .zero,
                      width: tableView.bounds.size.width,
                      height: dummyViewHeight))

    tableView.contentInset = UIEdgeInsets(top: .zero, left: .zero, bottom: -dummyViewHeight, right: .zero)
    return tableView
}

While thinking how to approach this problem, I remembered a very important detail about UITableViewStyleGrouped. The way UITableView implements the grouped style (the rounded borders around the cells) is by adding a custom backgroundView to the UITableViewCells, and not to the UITableView. Each cell is added a backgroundView according to its position in the section (upper rows get the upper part of the section border, middle ones get the side border and the bottom one gets – well, the bottom part). So, if we just want a plain style, and we don’t have a custom backgroundView for our cells (which is the case in 90% of the times), then all we need to do is use UITableViewStyleGrouped, and remove the custom background. This can be done by following those two steps:

将我们的tableView样式改为UITableViewStyleGrouped 在cellForRow返回单元格之前,添加以下一行:

细胞。开源视图=[[UIView alloc]这是一个细胞:跳跃]autorelease];

就是这样。tableView样式将变得完全像UITableViewStylePlain,除了浮动头。

希望这能有所帮助!