如何限制 SwiftUI 中文本的宽度

ray*_*eja 10 layout frame ios swift swiftui

我试图制作一个像这样的对话气泡:

Text("Hello my name is Johnny Miller and I am new here")
    .foregroundColor(.white)
    .padding()
    .background(.blue)
    .cornerRadius(25)
Run Code Online (Sandbox Code Playgroud)

然而我认为讲话泡泡看起来比实际需要的要宽得多。因此,我试图限制气泡在到达新线之前可以延伸多远。我想到的最简单的方法是:

Text("Hello my name is Johnny Miller and I am new here")
    .foregroundColor(.white)
    .padding()
    .background(.blue)
    .cornerRadius(25)
    .frame(maxWidth: 300)  // << Limits how wide it can stretch
Run Code Online (Sandbox Code Playgroud)

这适用于长消息,但当文本较小(例如“Hello”)时,框架将保持在 300 磅,并且拒绝将大小调整到理想宽度。

帧保持在300pts

我尝试使用.fixedSize(),但这会导致文本很长时被截断。

我找不到一种方法来限制文本的宽度并仍然保持其理想的大小。如果有人能提出解决方案,我将不胜感激。

简而言之:文本框架的宽度不应超过 300pts,但可以任意高。

提前致谢!

编辑

这些是我到目前为止尝试过的事情:

Text("Hello")
    .foregroundColor(.white)
    .padding()
    .background(.blue)
    .cornerRadius(25)
    .frame(maxWidth: 300)
    .lineLimit(nil)
Run Code Online (Sandbox Code Playgroud)

这会导致“Hello”气泡的帧为 300(我在上面提供了图像)

我尝试过:

Text("Hello my name is Johnny Miller and I am new here")
    .foregroundColor(.white)
    .padding()
    .background(.blue)
    .cornerRadius(25)
    .frame(maxWidth: 300)
    .lineLimit(nil)
    .fixedSize()
Run Code Online (Sandbox Code Playgroud)

这给了我:

截断的文本

小智 1

解决方案

设置文本视图的背景。为文本视图指定 maxWidth。

Text(message.content)
    .padding(.all,8)
    .background(Container()) // Container is a RoundedRectangle() with some styling
    .frame(maxWidth: 500, maxHeight: .infinity, alignment: .leading)
Run Code Online (Sandbox Code Playgroud)

给你这样的东西

解释

SwiftUI 中的文本视图会在需要时自动调整大小。

例子

您可以使用类似的方法为文本设置 maxWidth.frame(maxWidth: 500)

由于在设置 maxWidth 后文本大小已经具有我们想要的行为,因此我们可以通过将文本的背景设置为某个视图来为其提供一个“容器”。您还可以为其设置对齐方式和填充以匹配文本气泡效果,甚至自定义形状。

我刚刚创建了一个名为 Container() 的视图,它只是一个带有样式的 RoundedRectangle() 。

struct Container: View {
    var body: some View {
        RoundedRectangle(cornerRadius: 12, style: .continuous)
            .fill(Color.container.opacity(1))
            .blendMode(.multiply)
            .shadow(color: .white.opacity(0.4), radius: 1, x: 0, y: 0)
            .shadow(color: .black.opacity(0.1), radius: 4, x: 2, y: 4)
    }
}
Run Code Online (Sandbox Code Playgroud)