Home > Back-end >  Align Top In SwiftUI HStack
Align Top In SwiftUI HStack

Time:07-14

I am trying to align an image in the top of an HStack, but when the text is multiple lines the image gets centered. How can I align the second image with the top of the text?

var infoView: some View {
    VStack(alignment: .leading, spacing: 16) {
        HStack(alignment: .top) {
            Image("rocket")
                .frame(alignment: .top)
            Text("pqosejfr")
                .font(.body).fontWeight(.bold)
        }
        
        HStack {
            Image("bank")
            Text("qwoijqoiwjoijweijqwoiejqoiwjefoiqwjefoiqjwefijqwoiejfqoiwjefoiqwjefpoiqjweoifjqpwoiejfpqoiwejfoiqwejfoiqjwefpoiqjwepoifjqpwoiejfqpoiwejfpoqiwejfpoiqwjefpoiqwjefpoiqjweofijqwepoifjpqwoiejfoij")
                .font(.body).fontWeight(.bold)
        }
    }
}

enter image description here

CodePudding user response:

You can use a TextField with the multilineTextAlignment set to .leading.

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack(alignment: .leading, spacing: 16) {
            HStack(alignment: .top) {
                Image("rocket")
                    .frame(alignment: .top)
                TextField("pqosejfr", text: /* @START_MENU_TOKEN@ *//* @PLACEHOLDER=Value@ *//* @END_MENU_TOKEN@ */)
                    .font(.body).fontWeight(.bold)
            }
            
            HStack {
                Image("bank")
                TextField("qwoijqoiwjoijweijqwoiejqoiwjefoiqwjefoiqjwefijqwoiejfqoiwjefoiqwjefpoiqjweoifjqpwoiejfpqoiwejfoiqwejfoiqjwefpoiqjwepoifjqpwoiejfqpoiwejfpoqiwejfpoiqwjefpoiqwjefpoiqjweofijqwepoifjpqwoiejfoij", text: /* @START_MENU_TOKEN@ *//* @PLACEHOLDER=Value@ *//* @END_MENU_TOKEN@ */)
                    .font(.body).fontWeight(.bold)
                    .multilineTextAlignment(.leading)
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

CodePudding user response:

I was simply missing"

HStack(alignment: .top)

On the second HStack. Boneheaded mistake.

  • Related