5

I am trying to add padding to the left and right of a Text() view only. Ideally I would like to set it's width equal to the width of the device minus a constant I define.

For example:

Text("My text view here")
   .frame(width: device.width - 16)

What is the correct way to do this in SwiftUI? Am I approaching this the wrong way?

3 Answers 3

4

SwiftUI Standard way

GeometryReader is the type that gives you all information about the parent view

So you can use GeometryReader like:

    var body: some View {
        GeometryReader { geometry in
            Text("My text view here")
                .frame(width: geometry.size.width - 16)
                .background(Color.red) // This is just to see how it looks like
        }
    }

UIKit Aggressive way

You can get it directly from the device:

    var body: some View {
        Text("My text view here")
            .frame(width: UIScreen.main.bounds.width - 16)
            .background(Color.red) // This is just to see how it looks like
    }

Note that device width is physical and not updating on rotation. Also I haven't experimented with it to see myself, but I have read the UIScreen runs into problems on SplitView.

Sign up to request clarification or add additional context in comments.

6 Comments

Interesting - So you need to wrap the view in a GeometryReader in order to even get the width? This looks fairly inefficient.
It would be better to be something like an environment variable I think but this is how it works.
I added another way @StevenSchafer. Check that out.
your second answer is what I would expect to be able to do. Thanks!
He asked about width of device not the parent's view
|
0

Try setting the frame to the full width of the screen (maxWidth: .infinity) and then adding horizontal padding.

Text("My text view here")
        .frame(maxWidth: .infinity)
        .padding(.horizontal, 16)

Comments

-1

An alternate way to achieve the same thing is .padding(.horizontal, 16)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.