我正在构建一个iOS应用程序,部署目标12.1,swift 4.2。该应用程序使用容器视图,并在主屏幕的顶部有一个导航栏,最好在状态栏下方。在发布屏幕故事板中,我将Navigation Bar.top限制为Safe.Area.Top。这很好。但是在我将containerViewController设置为AppDelegate中的rootViewController之后,我将其限制在Main.storyboard(Navigation Bar.top到Safe.Area.Top)中的导航栏远远低于它应该的位置。
我可以让导航栏显示在状态栏正下方的唯一方法是在AppDelegate中为我的窗口创建一个自定义框架,其y值为负 - 这绝对不是我喜欢的解决方案。
这似乎产生的y值太低:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
window = UIWindow(frame: UIScreen.main.bounds)
let containerViewController = ContainerViewController()
window!.rootViewController = containerViewController
window!.makeKeyAndVisible()
return true
}
这是令人震惊的黑客攻击,让导航栏更接近它应该的位置:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
//window = UIWindow(frame: UIScreen.main.bounds)
let hackedFrame = CGRect(x: 0, y: -44, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
window = UIWindow(frame: hackedFrame)
let containerViewController = ContainerViewController()
window!.rootViewController = containerViewController
window!.makeKeyAndVisible()
//window!.windowLevel = UIWindow.Level.statusBar
return true
}
屏幕抓取:
我可能在这里遗漏了一些非常明显的东西,但我很感激任何人都能给予的帮助。
谢谢。
在iOS 11中,Apple在导航栏中引入了大型标题,这意味着它可以在拉动时拉伸。你应该尝试设置
navigationItem.largeTitleDisplayMode = .never
在viewDidLoad中,将导航栏的prefersLargeTitles设置为false
if #available(iOS 11.0, *) {
navigationItem.largeTitleDisplayMode = .always
navigationController?.navigationBar.prefersLargeTitles = true
}
尝试在ViewController中添加导航栏而不是AppDelegate,如下所示:
var screenWidth : CGFloat!
var screenHeight : CGFloat!
let screenSize: CGRect = UIScreen.main.bounds
在ViewDidLoad中:
screenWidth = screenSize.width
screenHeight = screenSize.height
navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 20, width: screenWidth, height: screenWidth / 3))
添加标题和按钮:
view.addSubview(navigationBar)
let navItem = UINavigationItem(title: "MainController")
let doneItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.cancel, target: nil, action: #selector(DismissViewController))
navItem.leftBarButtonItem = doneItem
UINavigationBar.appearance().barTintColor = .white
navigationBar.setItems([navItem], animated: false)