Bernd
Bernd

Reputation: 11493

Unintentional padding for some items in VStack

For my view I need some horizontal padding to be applied for all text content. The image on top should still be centered. The whole view is being presented inside a bottom sheet

Here's my code and the result as preview.

import SwiftUI

struct TestView: View {
    
    var body: some View {
        ScrollView {
            VStack(spacing: 20) {
                Image(systemName: "sparkles").font(.largeTitle)
                Text("Title ösdkföskdfj")
                    .fontWeight(.bold).font(.title2)
                + Text(" Special Term")
                    .fontWeight(.bold).font(.title2)
                    .foregroundColor(.accentColor)
                Text("lksdj flaksdjf ölaksdj flökasdj flökasjd flökasjd flökasjd fklöajs dflkjasdflökja sdlöfkj asldkfj alskdfj laskdjf lökasdj flökasj dflökjas dflkj asdlfkj asdlfkj asdlökfj asldökfj ")
            }
        }
        .padding(.top, 20)
        .padding(.horizontal, 60)
        .presentationDetents([.medium, .large])
    }
}

struct TestView_Previews: PreviewProvider {
    static var previews: some View {
        Group {
            TestView()
        }
    }
}

The layout should stay as is and not move around even with varying text content length.

The problem is that the first text shows up with some additional padding. How come? How can I remove this padding and have all text be algined?

Layout issue

Upvotes: 1

Views: 563

Answers (1)

Meritum
Meritum

Reputation: 101

This is because the VStacks default alignment is .center. You could give your title a maxWidth of .infinity and set a leading alignment if you want to preserve the current layout.

e.g.

                Group {
                    Text("Title ösdkföskdfj")
                        .fontWeight(.bold).font(.title2)
                    + Text(" Special Term")
                        .fontWeight(.bold).font(.title2)
                        .foregroundColor(.accentColor)
                }
                .frame(maxWidth: .infinity, alignment: .leading)

This would result in:

Result

Upvotes: 6

Related Questions