1 | initial version |
You can use the GeometryReader
and Text
modifiers to get the width of a Text
component in SwiftUI. Here's an example:
struct ContentView: View {
var body: some View {
GeometryReader { geometry in
Text("Hello, World!")
.font(.largeTitle)
.background(Color.yellow)
.onAppear {
print("Width of Text component: \(geometry.size.width)")
}
}
}
}
In this example, we use the GeometryReader
to get the size of the containing view, which we can then use to get the width of the Text
component. We add a background color to the Text
component using the .background
modifier to make it easier to see the component's bounds. Finally, we use the .onAppear
modifier to print the width of the component when it appears on the screen.