I want to add text (eg. Hi) in a shape (eg. Square) in SwiftUI and make them act as a single object.
It looks like there's no direct way to add text in shape in SwiftUI.
I want to add text (eg. Hi) in a shape (eg. Square) in SwiftUI and make them act as a single object.
It looks like there's no direct way to add text in shape in SwiftUI.
Here is what I consider to be a more comprehensive answer. This will work as of Xcode 11.5:
Text(question)
.fixedSize(horizontal: false, vertical: true)
.multilineTextAlignment(.center)
.padding()
.frame(width: 300, height: 200)
.background(Rectangle().fill(Color.white).shadow(radius: 3))
Notes:
The end result of this example is the text looks to appear within a cue card like shape!
Here is, IMO, most simple approach:
Generic schema
Text(_any_of_text_)
.background(_any_of_Shape)
eg:
Text("Hello, World!")
.background(Rectangle().stroke())
Text("Hello, World!")
.background(RoundedRectangle(cornerRadius: 4).stroke())
Using Swift built-in shapes such as Capsule()
, RoundedRectangle()
and etc. Then, you can apply .overlay
to the shape. The overlay take in any view such as text
.
var body: some View {
Capsule()
.fill(Color.blue)
.overlay(
Text("Hello World")
)
}
Create a new SwiftUI View and make use of a Z-Stack to create your goal.
struct YourCustomObject: View {
var body: some View {
ZStack {
Rectangle()
.fill(Color.secondary)
.frame(width: 200, height: 200)
Text("Your desired text")
.foregroundColor(.white)
}
}
}
Text("Hi")
.frame(width: 40, height: 40, alignment: .center)
.background(Color.black)
.clipShape(Rectangle())
Using ZStack you can, but the text might spill from the rectangle so you use
.offset()
E.g:
ZStack {
RoundedRectangle(cornerRadius: 11)
.stroke(Color("color5"), lineWidth: 1)
.frame(width: .infinity, height: 60)
VStack(alignment: .leading) {
Text("Adewale")
.multilineTextAlignment(.leading)
.foregroundColor(Color("color5"))
.offset(x: -95 )
}
}
use the .offset()
to tweak the location of the Text view on the RoundedRectangle view.
© 2022 - 2024 — McMap. All rights reserved.