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

时光怂恿深爱的人放手 提交于 2020-07-19 04:44:29

问题


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...).

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:

  • https://stackoverflow.com/a/51295457/4061501
  • https://stackoverflow.com/a/48388588/4061501

But none of them are worked on iOS 13.


回答1:


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.




回答2:


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```


来源:https://stackoverflow.com/questions/62588368/how-to-convert-navbar-large-title-to-multi-line-centre-aligned

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!