首页 > 解决方案 > 为 SwiftUI 文本视图提供固定宽度并使文本换行到不定高度

问题描述

主要编辑澄清问题

我想要什么:对于Text与屏幕左侧或右侧对齐的视图,以扩展到某个最大宽度,并且当文本达到该长度时,它不会超过该长度。当要显示的文本变得太长时,Text视图只是简单地增加高度以考虑额外的文本。这方面的一个例子是在 Apple 的 Messages 应用程序中:发送的消息一直向右对齐,但即使它们很长,它们的左边仍然有一个空白区域(聊天气泡的宽度只有 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)

                }
            }
        }
        
    }
}

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

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

标签: swiftswiftui

解决方案


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)
            }

推荐阅读