将UIScreen.main.bounds用作UIWindow框架时,UINavigationBar太低

时间:2019-04-12 19:26:48

标签: ios swift uinavigationbar appdelegate uiscreen

我正在构建一个iOS应用,部署目标为12.1,速度为4.2。该应用程序使用容器视图,并在主屏幕顶部(最好在状态栏正下方)具有导航栏。在启动屏幕情节提要中,我将Navigation Bar.top限制为Safe.Area.Top。很好但是,在我将containerViewController设置为AppDelegate中的rootViewController之后,在Main.storyboard中将其约束(Navigation Bar.top到Safe.Area.Top)的导航栏显示在其应有的下方。

使导航栏显示在状态栏正下方的唯一方法是在AppDelegate中为我的窗口创建一个自定义框架,该框架的y值为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
    }

屏幕抓取:

launchscreen, navbar correct

main screen post didFinishLaunchingWithOptions, navbar too low

我可能在这里确实缺少一些明显的东西,但是我很感谢任何人都能提供的帮助。

谢谢。

2 个答案:

答案 0 :(得分:0)

在iOS 11中,Apple在导航栏中引入了大标题,这意味着如果拉动它可以将其拉伸。您应该尝试设置

navigationItem.largeTitleDisplayMode = .never

在您的viewDidLoad中,将导航栏的preferredsLargeTitles设置为false

if #available(iOS 11.0, *) {
   navigationItem.largeTitleDisplayMode = .always
   navigationController?.navigationBar.prefersLargeTitles = true
} 

答案 1 :(得分:0)

尝试在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)