How to convert Navbar Large title to Multi-line, centre aligned

Viewed 766

I'm trying to design view controller with Multi-lined centred Large title text exactly like Ask Siri by apple (Settings->General->Keyboards->About Ask Siri, Dictation and Privacy...).

Settings->General->Keyboards->About Ask Siri On scroll

I can able to achieve centred text using:

let paragraph = NSMutableParagraphStyle()
paragraph.alignment = .center
navigationController?.navigationBar.largeTitleTextAttributes = [.paragraphStyle: paragraph]

I did set Navigation title from Storyboard and tried these to achieve multi-lined large title:

But none of them are worked on iOS 13.

2 Answers

You can achieve this by adding a multiline label to your scrollView and then show/hide your navigation item title in the scrollViewDidScroll delegate method of the scrollView depending on the vertical scrollView offset.

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if scrollView.contentOffset.y > myLabelHeight && navigationItem.title == "" {
        setTitle(hidden: false)
    } else if scrollView.contentOffset.y <= myLabelHeight && navigationItem.title == "MyTitleString" {
        setTitle(hidden: true)
    }
}

I've added a layer transition to achieve the fade effect.

func setTitle(hidden: Bool) {
    let animation = CATransition()
    animation.duration = 0.25
    animation.type = .fade

    navigationController?.navigationBar.layer.add(animation, forKey: "fadeText")

    if hidden {
        navigationItem.title = ""
    } else {
        navigationItem.title = "MyTitleString"
    }
}

Don't forget to set the navigation item title to an empty string in viewDidLoad.

There is not any such kind of property that you can set and title became multiline. You need to manipulate it.

This is a code example of how you can create a multiline navigationBar title:

label.backgroundColor = .clear
label.numberOfLines = 2
label.font = UIFont.boldSystemFont(ofSize: 16.0)
label.textAlignment = .center
label.textColor = .white
label.text = "This is a\nmultiline string for the navBar"
self.navigationItem.titleView = label```
Related