Text in SwiftUI Form not wrapping after being changed

流过昼夜 提交于 2021-02-08 06:40:12

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/65676540/text-in-swiftui-form-not-wrapping-after-being-changed

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