基本视图 UI 导航栏对方向的响应

Base view UI nav bar responsiveness to orientation

我是使用 Swift 和 Xcode 进行 iOS 应用程序开发的超级新手。现在,我正在尝试为我的所有视图创建一个带有导航栏的基本视图,而不是使用导航控制器。当我以横向模式开始时,导航栏看起来不错,但当我切换到纵向模式时,高度看起来不对。当我以纵向模式启动时,横向模式会关闭导航栏只有全长一半的位置。似乎当我更改为横向模式时,没有绘制导航栏并且它使用旧的...在下面的代码中,我有一个方向侦听器再次绘制导航栏,但它似乎不起作用。

import UIKit

class BaseViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(BaseViewController.rotated), name: UIDevice.orientationDidChangeNotification, object: nil)
    }

    deinit {
       NotificationCenter.default.removeObserver(self, name: UIDevice.orientationDidChangeNotification, object: nil)
    }

    @objc func rotated() {
        if UIDevice.current.orientation.isLandscape {
            print("Landscape")
            createNavBarLandscape()
        } else {
            print("Portrait")
            createNavBarPortrait()
        }
    }
    
    func createNavBarLandscape() {
        let navBar = UINavigationBar(frame: CGRect(x: 0, y: 50, width: view.frame.size.width * 2, height: 24))
        view.addSubview(navBar)
        
        navBar.barTintColor = .white
        let navItem = UINavigationItem(title: "logo")
        let logo = UIImage(named: "logo.png")
        let imageView = UIImageView(image:logo)
        navItem.titleView = imageView
        navBar.setItems([navItem], animated: false)
    }
    
    func createNavBarPortrait() {
        let navBar = UINavigationBar(frame: CGRect(x: 0, y: 50, width: view.frame.size.width, height: 44))
        view.addSubview(navBar)
        
        navBar.barTintColor = .white
        let navItem = UINavigationItem(title: "logo")
        let logo = UIImage(named: "logo.png")
        let imageView = UIImageView(image:logo)
        navItem.titleView = imageView
        navBar.setItems([navItem], animated: false)
    }
}

以纵向模式启动:
人像模式:

横向模式:

以横向模式启动:
横向模式:

人像模式:

试试这个...

class MyBaseViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let navBar = UINavigationBar()
        view.addSubview(navBar)
        
        navBar.barTintColor = .white
        let navItem = UINavigationItem(title: "logo")
        let imageView = UIImageView()
        if let logo = UIImage(named: "logo") {
            imageView.image = logo
        }
        navItem.titleView = imageView
        navBar.setItems([navItem], animated: false)

        navBar.translatesAutoresizingMaskIntoConstraints = false
        
        // respect safe area
        let g = view.safeAreaLayoutGuide
        
        NSLayoutConstraint.activate([
            navBar.topAnchor.constraint(equalTo: g.topAnchor),
            navBar.leadingAnchor.constraint(equalTo: g.leadingAnchor),
            navBar.trailingAnchor.constraint(equalTo: g.trailingAnchor),
        ])
        
    }

}