I try to center the title in large title mode, but that code doesn't affect. In AppDelegate:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
UINavigationBar.appearance().largeTitleTextAttributes = [NSAttributedStringKey.paragraphStyle: paragraphStyle]
return true
}
The large title cannot be centered, it has it´s position to the left and is left aligned. The size of the title does not matter, if you want the title centred you have to create your own custom one.
I solved this by making the navigationItem title to none. Then setting a custom label with my text and adding constraints to the label programmatically. Here is the code below.
override func setupNavigationBar() {
navigationItem.title = .none
if #available(iOS 11.0, *) {
navigationController?.navigationBar.prefersLargeTitles = true
let titleLabel = UILabel()
titleLabel.text = "Home"
titleLabel.translatesAutoresizingMaskIntoConstraints = false
let targetView = self.navigationController?.navigationBar
targetView?.addSubview(titleLabel)
titleLabel.anchor(top: nil, left: nil, bottom: targetView?.bottomAnchor, right: nil, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 222, height: 40)
titleLabel.centerXAnchor.constraint(equalTo: (targetView?.centerXAnchor)!).isActive = true
} else {
// Fallback on earlier versions
}
}
UINavigationBar automatically centers its titleView as long as there is enough room. I suppose your code won't affect actual titleView frame because you don't have back button or rightBarButton, so UINavigationBar automatically prolong titleView to the right.
To fix it you can add empty right bar button, or add custom titleView with predefined frame
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.