简体   繁体   English

大标题,居中对齐

[英]Large title, center alignment

I try to center the title in large title mode, but that code doesn't affect. 我尝试以大标题模式将标题居中,但是该代码不受影响。 In AppDelegate: 在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. 我通过将navigationItem标题设置为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. 只要有足够的空间, UINavigationBar就会自动将其titleView居中。 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. 我想您的代码不会影响实际的titleView框架,因为您没有后退按钮或rightBarButton,因此UINavigationBar会自动将titleView延长到右边。

To fix it you can add empty right bar button, or add custom titleView with predefined frame 要解决此问题,您可以添加空的右栏按钮,或添加具有预定义框架的自定义titleView

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM