将 UIView 添加到 TableViewControllers 视图

Adding a UIView to a TableViewControllers view

我有一个表ViewController,我在其中以编程方式创建了一个 UIView,它是状态栏的宽度和高度,并具有彩色背景。基本上,它用作状态栏的背景:

let statusBarBG = UIView(frame: CGRectMake(0, 0, widthOfScreen, 20))
statusBarBG.backgroundColor = UIColor...
self.view.addSubView(statusBarBG)

但是,当我上下拖动 table 时,此状态栏背景会随着整个 table 视图移动,如下图所示(左侧是正常情况,红色的较大部分是我的导航栏的 bg):

所以我的问题是:我如何在 tableViewController 中创建一个视图,它更像是 tableView 的同级视图而不是随它移动的子视图?谢谢

how do I create a view inside this tableViewController that is more like a sibling to the tableView rather than a child that moves with it?

不幸的是,这对于 tableviewcontroller 是不可能的,因为 tableviewcontroller 的视图是一个 UITableView 实例,它又是UIS 滚动视图。基本上任何你作为滚动视图的 child 放置的东西都会随之滚动。

更好的方法是不再使用 tableviewcontroller,而是使用带有嵌入式 table 视图的普通视图控制器。您甚至可以通过将视图控制器添加到层次结构来重用它。

另一种(更简单)的方法是处理uitable视图的滚动委托方法,并根据偏移量调整header视图的Y位置。

如果您只希望该视图充当背景色,则可以只使用图像。

[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navigationbar.png"] forBarMetrics:UIBarMetricsDefault];

如果您只想要一种颜色而不是自定义图像,或者使用 imageWithColor...在您的图片中,您似乎想要整个导航栏 + 状态栏只是红色...所以这段代码适用于整个导航栏 + 状态栏...如果你想要不同的状态栏只需设计一个图像并使用该代码...我不是 swift 抱歉,但它应该非常相似...

编辑:啊,你不在导航控制器中使用那个 tableView 吗?那么它可能不起作用...

编辑 2:

这是我的头像

使用此代码

[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navigationbar.png"] forBarMetrics:UIBarMetricsDefault];

我得到

没有它只是干净

试试这个:

    let bottomView = UIView()
    bottomView.backgroundColor = .red // or your color
    bottomView.frame = CGRect(x: 0, y: UIScreen.main.bounds.size.height - 78, width: tableView.frame.size.width, height: 78) // 78 or your size of view
    navigationController?.view.addSubview(bottomView)
    tableView.tableFooterView = UIView()