【问题标题】:Make a TableHeaderView not scrolling使 TableHeaderView 不滚动
【发布时间】:2026-02-23 07:00:02
【问题描述】:

我制作了一个带有原型单元格的 TableView;在 tableView 的第一个位置我做了这个

override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    if section == 0
    {
        let view : UIView = UIView(frame: CGRectMake(0, 0, 400, 140))
        view.backgroundColor = UIColor.redColor()
        view.addSubview(populateView())
        //populateView() is a method by which I programmatically made all object in the view (label, images, textView)
        return view
    }
    else
    {
        return nil
    }
}

override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat
{
    if section == 0
    {
        return 140
    } else
    {
        return 0
    }
}

结果是这样的(这是一个测试):

现在我想让 TableHeaderView 不随 tableView 滚动;我将 tableView 样式设置为简单;我找到了这个Change Default Scrolling Behavior of UITableView Section Header 和这个https://corecocoa.wordpress.com/2011/09/17/how-to-disable-floating-header-in-uitableview/,但我不知道Objective-c(我是6 个月以来的快速程序员)。谁能解决我的问题?

【问题讨论】:

    标签: swift uitableview cells tableheader


    【解决方案1】:

    解决方案是使用UIViewController,而不是UITableViewController。表格视图控制器将占用整个 view 并且上面没有空间。

    相反,您必须使用UIViewController,添加一个子视图作为标题,并添加一个UITableView 作为子视图。您可以通过显式包含数据源和委托协议来填充它并与之交互。

    class HeaderTableViewController : UIViewController, 
                                      UITableViewDataSource, UITableViewDelegate
    

    【讨论】:

      【解决方案2】:

      我肯定会使用 UIViewController 与 UITableView 和它上面的自定义视图(见下文)。

      或者如果你想使用 UITableViewController(它带来了一些额外的功能),你可以使用容器视图将它嵌入到标题下。

      【讨论】:

      • 嗯,也许第一个选项更简单。但是如果你想使用 UITableViewControllers,那么你基本上可以在加载时将信息传递给 tableViewController——使用“self.childViewControllers.first”或在“performSegue:”方法中获取指向嵌入式 UITableViewController 的指针。 (嵌入控制器只是一种特殊的 segue)
      • 我看不出这个答案比我 2 小时前给出的答案有何改进。