SwiftUI 表单中的文本在更改后不换行 [英] Text in SwiftUI Form not wrapping after being changed

查看:40
本文介绍了SwiftUI 表单中的文本在更改后不换行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 SwiftUI 表单中显示一些文本,这些文本会根据当前状态而改变.但是,如果新"文本比表单第一次出现时显示的原始字符串长,它不会正确换行.

在下面的示例中,打开切换开关会更改正在显示的文本,但它会被截断而不是换行

<预><代码>结构内容视图:查看{@State var showLongString = falsevar主体:一些视图{形式 {部分 {Text(showLongString ?这是一个太长的字符串,不能放在一行中":你好,世界!")}部分 {Toggle("显示长字符串", isOn: $showLongString)}}}}

我能找到的唯一解决方法是使用 .listRowInsets 并增加尾随插入,这并不理想,并且会根据不同缩放的设备执行不同的操作(即它可能会包裹在iPhone 12 但不在 iPhone 11/XR 上),无需进一步增加尾随插入.

是否有其他解决方法可以解决此问题?

解决方案

你可以使用 fixedSize 但限制它只能垂直扩展:

Section {Text(showLongString ? "这是一个太长的字符串,无法在一行中显示,这是一个太长的字符串,无法在一行中显示":"Hello, World!").fixedSize(水平:假,垂直:真)}.id(showLongString)

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?

解决方案

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)

这篇关于SwiftUI 表单中的文本在更改后不换行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆