Darren
Darren

Reputation: 10398

SwiftUI Size to fit or word-wrap navigation title

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?

Upvotes: 4

Views: 2705

Answers (2)

dvs
dvs

Reputation: 12432

Building on Jose's answer, if you want to apply this to all navigation titles throughout your app, place the line in the init of your App struct:

@main
struct MyApp: App {
    init() {
        UILabel.appearance(whenContainedInInstancesOf: [UINavigationBar.self]).adjustsFontSizeToFitWidth = true
    }
}

Upvotes: 2

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")
        }
    }
}

Upvotes: 9

Related Questions