Swift:使嵌入在导航控制器中的UITableViewController的背景图片填满整个屏幕

问题描述

我设法在嵌入导航控制器的 UITableViewController 中创建了半透明和圆形的 UITableViewCells,在 viewDidLoad() 中使用这行代码

    tableView.backgroundView = UIImageView(image: UIImage(named: "nightTokyo"))

Background image does not fill entire phone screen

但我希望背景图片填满整个手机屏幕。我将代码(并且这行代码)更改为:

    navigationController?.view = UIImageView(image: UIImage(named: "nightTokyo"))

现在背景图片填满了整个手机屏幕,但我的桌子,甚至 iPhone 的时间和电池指示器图标都不见了。

Background image fills the entire phone screen but everything else is missing

我想要的是背景图像填满整个屏幕,但 tableView、它的单元格、iPhone 时间、电池电量图标等保持显示

解决方法

navigationController?.setNavigationBarHidden(true,animation: true)

,

以下是我使用 Swift 5、XCode 12 所做的工作。

第 1 步(可选)- 创建自定义 UINavigationController 类

Last

用这个 UINavigationController 子类替换你的 UINavigationController。我将此标记为可选,因为这是基于偏好的,如果您不设置它,您的导航栏将不透明,您将看不到它下面的内容。

设置 class CustomNavigationController: UINavigationController { override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationBar.isTranslucent = true } 可以让您看到它下方的背景,这正是我喜欢的。子类也是可选的,但您可能需要对导航栏进行其他更新,因此我总是喜欢将其设为子类。

第 2 步 - 设置背景视图限制

navigationBar.isTranslucent = true

在设置约束之前: UIViewController without NavBar top constraints

设置上述约束后: UIViewController with NavBar top constraints