Nick Kohrn
Nick Kohrn

Reputation: 6049

How Can I Wrap Text in a SwiftUI NavigationButton?

SwiftUI's Text type has a modifier that allows text to wrap if the text is too long to fit horizontally within its container. To achieve text wrapping, simply pass nil as the argument to the lineLimit modifier:

Text("This text is too long to fit horizontally within its non-NavigationButton container. Therefore, it should wrap to fit, and it does.")
    .font(.body)
    .lineLimit(nil)

The above works as expected, except for when used inside of a SwiftUI NavigationButton. All Text instances that I have nested within NavigationButton instances do not wrap:

NavigationButton(destination: DestinationView()) {
    Text("This text is too long to fit horizontally within its NavigationButton container. Therefore, it should wrap to fit, but it does not.")
        .font(.body)
        .lineLimit(nil)
}

Is there anything that I am missing from the code above that would allow Text instances to wrap within NavigationButton instances?

Edit to add more context:

The initial view is a List that is wrapped in a NavigationView. The List contains instances of MeasurableItemsListItem, which are wrapped in NavigationButton instances that trigger navigation to a secondary view that is added to the navigation stack:

struct MeasurableItemsList : View {

    private let measurableItems = MeasurableItem.allCases

    var body: some View {
        NavigationView {
            List(measurableItems.identified(by: \.self)) { measurableItem in
                NavigationButton(destination: DosableFormsList(measurableItem: measurableItem)) {
                    MeasurableItemsListItem(measurableItem: measurableItem)
                }
            }
        }
    }
}

Each list item that is wrapped in a NavigationButton is made from the following structure:

struct MeasurableItemsListItem : View {

    let measurableItem: MeasurableItem

    var body: some View {
        Text(measurableItem.name)
            .font(.body)
            .foregroundColor(.primary)
            .lineLimit(nil)
    }

}

Upvotes: 1

Views: 948

Answers (2)

Wil Shipley
Wil Shipley

Reputation: 9543

You might be helped with this answer: https://stackoverflow.com/a/56604599/30602

The summary is that inside other Builders you need to add .fixedSize(horizontal: false, vertical: true) to your Text() to get it to wrap.

Upvotes: 3

mohit kejriwal
mohit kejriwal

Reputation: 1835

You don't need to use NavigationButton to achieve navigation. You can achieve it by using NavigationLink easily, wherein you don't need to wrap your views inside NavigationButton. Check this ANSWER which is explaining the usage of NavigationLink without wrapping view inside it. I hope it helps. P.S.- i don't have enough reputation points to add this as a comment. Thanks

Upvotes: 0

Related Questions