I want to create navigation controller and navigation bar programatically. I want to change height and items size and position. My navigation bar height = 74 and item size = 50×50. Also item top space = 12 and bottom = 12. I trying to do it with this code:
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
if let windowScene = (scene as? UIWindowScene) {
let window = UIWindow(windowScene: windowScene)
let navigationController = UINavigationController()
let viewController = ViewController()
navigationController.viewControllers = [viewController]
window.rootViewController = navigationController
self.window = window
window.makeKeyAndVisible()
}
}
ViewController
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.navigationController?.navigationBar.backgroundColor = .gray
self.navigationController?.navigationBar.frame.size.height = 74
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
let menuBtn = UIButton(type: .custom)
menuBtn.frame = CGRect(x: 0.0, y: 12.0, width: 50, height: 50)
menuBtn.setImage(UIImage(named:"mute"), for: .normal)
let menuBarItem = UIBarButtonItem(customView: menuBtn)
menuBarItem.customView?.widthAnchor.constraint(equalToConstant: 50).isActive = true
menuBarItem.customView?.heightAnchor.constraint(equalToConstant: 50).isActive = true
menuBarItem.setBackgroundVerticalPositionAdjustment(12.0, for: .default)
self.navigationItem.rightBarButtonItem = menuBarItem
}
But it doesn’t work. I don’t see the height of the navigation bar changed, nor the size and position of the navigation buttons. How to solve a problem?
2
Answers
Try this instead.
You can just wrap your viewController in a UINavigationController when you’re setting the rootViewController.
There is no way to increase navigation bar height. But instead, we can use private API, called "_UINavigationBarPalette", used in Apple apps, such as Calendar and Fitness.
Please note, that I split raw strings to bypass AppStore static analyser. Otherwise your app will be rejected due to private API usage.
Source: https://x.com/search?q=_UINavigationBarPalette&src=typed_query