为 SwiftUI Text 视图提供固定宽度并使文本换行至不定高度

Kyl*_*bbs 5 swift swiftui

澄清问题的主要编辑

我想要的:对于与Text屏幕左侧或右侧对齐的视图扩展到某个最大宽度,并且当文本达到该长度时,它不会超出该长度。当要显示的文本太长时,视图Text只是简单地增加高度以容纳额外的文本。Apple 的消息应用程序就是一个这样的例子:发送的消息一直向右对齐,但即使它们很长,左侧仍然有一个空白空间(聊天气泡的宽度仅达到 75%)屏幕的宽度)。

我有一些硬编码值的代码来提供示例:

struct ContentView: View {
    let messages = [
        "Hello.",
        "Hi",
        "Text so long that it could reach all the way to the other side of the screen, we only want it to take up a width of about 75% of the screen though starting from the left. That is the main issue of this post.",
        "Yeah. This message is also long enough to take up the full width of the screen, but for this one we want it to take up 75% of the screen starting all the way on the right side.",
        "What are we gonna do.",
        "IDK."
    ]
    
    var body: some View {
        VStack {
            List {
                ForEach(0...5, id: \.self) { number in
                    Text(messages[number])
                        .frame(maxWidth: .infinity, alignment: number % 2 == 0 ? .leading : .trailing)

                }
            }
        }
        
    }
}
Run Code Online (Sandbox Code Playgroud)

所以我几乎得到了我想要的,所有其他消息都是正确对齐的。但是,当视图中的字符串Text很长时,视图的宽度会在高度开始扩展之前一直扩展Text。我希望宽度在高度开始扩展之前仅扩展一定量。

我知道扩展视图宽度Text以适应文本是正常行为,但我想知道是否有办法改变它。我唯一能想到尝试的是更改maxWidth,但这只会导致 的右边缘.trailing Text移到左侧,这是不需要的。

Yod*_*ama 4

ForEach(previouslyPlayed, id: \.self) { data in
                Text(data.text)
                .lineLimit(nil)
                .multilineTextAlignment(.trailing)
                .foregroundColor(ColorManager.mainText)
                .font(.custom("Courier New", size: 14))
                .fixedSize(horizontal: false, vertical: true)
            }
Run Code Online (Sandbox Code Playgroud)