Helloyunho
Helloyunho

Reputation: 33

SwiftUI HStack top alignment doesn't work

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)
        )
    }
}

Upvotes: 2

Views: 5935

Answers (1)

Asperi
Asperi

Reputation: 257503

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 !!

Upvotes: 11

Related Questions