Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI HStack top alignment doesn't work

Tags:

swift

swiftui

I was trying to align Text (Test in the picture) in HStack to top, but HStack align doesn't work. It's still in the center.

Picture

Here's my code:

struct ContentView: View {
    var body: some View {
        VStack {
            HStack(alignment: .top) {
                Text("Test")
                    .font(.largeTitle)
                    .fontWeight(.bold)
                    .multilineTextAlignment(.leading)
                Spacer()
            }
            .frame(width: 480, height: 160)
            HStack {
                Text(
                    "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Neque volutpat ac tincidunt vitae semper quis lectus nulla at. Metus vulputate eu scelerisque felis imperdiet proin fermentum. Viverra accumsan in nisl nisi scelerisque. Aliquet sagittis id consectetur purus ut faucibus pulvinar elementum."
                )
                .font(.body)
                .foregroundColor(Color.black)
                .multilineTextAlignment(.leading)
                .frame(
                    minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity,
                    alignment: .topLeading
                )
                .padding()
            }
            .frame(width: 480, height: 320)
            .background(Color(.white))
        }
        .frame(width: 480, height: 480)
        .background(
            ZStack {
                Rectangle()
                    .fill(
                        LinearGradient(
                            gradient: Gradient(colors: [.blue, .red]),
                            startPoint: .topLeading,
                            endPoint: .bottomTrailing
                        )
                    )
                    .blur(radius: 10)

                VisualEffectView(
                    material: .toolTip,
                    blendingMode: .withinWindow
                )
            }
        )
        .mask(
            RoundedRectangle(cornerRadius: 30)
        )
    }
}
like image 747
Helloyunho Avatar asked Jun 13 '26 20:06

Helloyunho


1 Answers

You need to add alignment in frame

        HStack {
            Text("Test")
                .font(.largeTitle)
                .fontWeight(.bold)
                .multilineTextAlignment(.leading)
            Spacer()
        }
        .frame(width: 480, height: 160, alignment: .top)   // << here !!
like image 164
Asperi Avatar answered Jun 17 '26 04:06

Asperi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!