问题描述
我正在开发一个项目,在该项目中我在 SwiftUI 中使用了不同的形状,例如这个 RoundedRectangle。 我想通过叠加在其上添加文本,但它不允许我添加多于一行。我试图搜索一些叠加教程,但总是找到只显示 -one life of text - 示例的教程。
所以我想知道是否有办法在这样的形状上添加多行文本叠加,或者是否有更好的方法来处理它。
感谢您的反馈。
这是当前代码:
import SwiftUI
struct ContentView: View {
var body: some View {
HStack {
RoundedRectangle(cornerRadius: 20)
.frame(width: 320,height: 200)
.foregroundColor(Color.blue)
.overlay(
Text("Hello there")
)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
这是我理想中想要的,但这样就行不通了:
import SwiftUI
struct ContentView: View {
var body: some View {
HStack {
RoundedRectangle(cornerRadius: 20)
.frame(width: 320,height: 200)
.foregroundColor(Color.blue)
.overlay(
Text("Hello there")
Text("Hello there")
Text("Hello there")
Text("Hello there")
Text("Hello there")
Text("Hello there")
)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
解决方法
将您的文本与 Group
、VStack
、HStack
等中的任何一个包装在一个容器中。
struct ContentView: View {
var body: some View {
HStack {
RoundedRectangle(cornerRadius: 20)
.frame(width: 320,height: 200)
.foregroundColor(Color.blue)
.overlay(
Group{ //<-- Here
Text("Hello there")
Text("Hello there")
Text("Hello there")
Text("Hello there")
Text("Hello there")
Text("Hello there")
}
)
}
}
}
或者您可以使用 @ViewBuilder
struct ContentView: View {
var body: some View {
HStack {
RoundedRectangle(cornerRadius: 20)
.frame(width: 320,height: 200)
.foregroundColor(Color.blue)
.overlay(
overlayView
)
}
}
// Make your view here
@ViewBuilder
private var overlayView: some View {
Text("Hello there")
Text("Hello there")
Text("Hello there")
Text("Hello there")
Text("Hello there")
Text("Hello there")
}
}