Search code examples
textswiftuiwidth

SwiftUI, How to set Text width correctly?


I have a very simple ContentView, The Text's width set to 68

struct ContentView: View {
    var body: some View {
        VStack {
            Text("Hello, world!")
                .frame(width: 68)
        }
        .padding()
    }
}

But in Debug View Hierarchy I can see the Text's width is not 68 at all, instead, the wrapper width of the Textis 68. Did I miss something? enter image description here

enter image description here


Solution

  • Text isn't greedy by default and won't take all the space it's got available to it unless it's needed. Due to the extra width not being needed, it won't use it.

    The width of the VStack is 68 as it's sized based on the size of it's child views, in this case it's only child view is explicitly saying it's width is 68, so the width of the VSTack will be 68 and since the Text isn't greedy in this case, it'll only take up the horizontal space that it needs. This leads to the width of the Text being less than the width of the VSTack.

    If you don't explicitly set the width of the Text you will see that the width of the VStack will match the width of the view it contains.