SwiftUI Size to fit or word-wrap navigation title

Viewed 659

I have a navigation title that is too large on some smaller devices. I've read many ways to set the titleTextAttributes and largeTitleTextAttributes of the UINavigationBar.appearance() however when setting the paragraph style to word wrap, it seems to remove the standard ... clipping and have the text continue off the edge of the screen without wrapping:

init() {
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.lineBreakMode = .byWordWrapping
    UINavigationBar.appearance().largeTitleTextAttributes = [
        .paragraphStyle: paragraphStyle
    ]
}

I want to maintain the SwiftUI behaviour where the title is shown as large text until the view is scrolled up and it moves to the navigation bar, so getting the .toolbar directly won't help.

I also don't want to just specify a smaller font as I only want it to shrink or wrap if necessary.

Has anyone managed to achieve this?

1 Answers

You can add this line on the initializer of the view where yo have the issue

UILabel.appearance(whenContainedInInstancesOf: [UINavigationBar.self]).adjustsFontSizeToFitWidth = true

Example:

struct YourView: View {
    init() {
        UILabel.appearance(whenContainedInInstancesOf: [UINavigationBar.self]).adjustsFontSizeToFitWidth = true
    }

    var body: some View {
        NavigationView {
            Text("Your content")
                .navigationBarTitle("Very very large title to fit in screen")
        }
    }
}
Related