Search code examples
iosswiftswiftuiswiftui-listswiftui-form

Text in SwiftUI Form not wrapping after being changed


I need to display some text in a SwiftUI Form that will change depending on the current state. However, if the "new" text is longer than the original string displayed when the form first appeared, it won't wrap correctly.

In the example below, turning the toggle on changes the text being displayed, but it gets truncated instead of wrapping


struct ContentView: View {
    @State var showLongString = false
    
    var body: some View {
        
        Form {
            
            Section {
                Text(showLongString ? "This is a string that is too long to fit in one line" : "Hello, World!")
                
            }
            Section {
                Toggle("Show long string", isOn: $showLongString)
            }
        }
    }
    
}

The only workaround I can find is to use .listRowInsets and increase the trailing inset, which isn't ideal, and will perform differently depending on devices which scale differently (i.e. it may wrap on the iPhone 12 but not on the iPhone 11/XR), without further increasing the trailing inset.

Is there any other workaround for this problem?


Solution

  • You can use fixedSize but limit it to expand vertically only:

    Section {
        Text(showLongString ? "This is a string that is too long to fit in one line, This is a string that is too long to fit in one line" : "Hello, World!")
            .fixedSize(horizontal: false, vertical: true)
    }
    .id(showLongString)