Reputation: 437
I am working on a project where I use different shapes in SwiftUI, for example, this RoundedRectangle. I want to add text on it through overlay but it doesn’t let me add more than one line. I tried to search for some tutorials for overlay but always found ones showing just -one life of text - example.
So I was wondering if there’s a way to add multiple lines of text overlay on shapes like that or if there is some better way to approach it.
Thank you for your feedback.
Here’s the current code:
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()
}
}
And here’s what I would ideally like, but this way it doesn’t work this way:
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()
}
}
Upvotes: 0
Views: 1529
Reputation: 18994
Wrapped your text with anyone of them Group
, VStack
, HStack
, etc. in one container.
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")
}
)
}
}
}
Or you can use @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")
}
}
Upvotes: 1