Search code examples
swiftuivstackhstackswiftui-alignment-guide

How to set HStack child alignment different


I have HStack with two views: Image and Text. I would like to align Image top but the text center on VerticalAlignment. However, specifying alignment .center for the Text does not do the trick , it is still positioned top. Is there anything I am missing?

struct SwiftUIView: View {
    var body: some View {
        HStack(alignment: .top) {
            Image(systemName: "star.fill")
                .resizable()
                .frame(width: 100, height: 100)
                .background(.green)

            HStack(alignment: .center) {
                Text("Text that has dynamic height and should be aligned center")
                    .background(.pink)
            }
        }
        .background(.gray)
    }
}

Preview screenshot


Solution

  • If I understand correctly, you want the image to be aligned to the top of the HStack when the text is taller than the image, and you want the text to be centered vertically when the text is shorter than the image.

    Instead of wrapping the text in another HStack, you should add a frame around the text.

    Text("Text that has dynamic height and should be aligned center")
        .background(.pink)
        .frame(minHeight: 100, alignment: .center)
    

    This (invisible) frame should be at least as tall as the image (100pt), and the text should have .center alignment inside that frame.

    .center is the default value for alignment:, so writing .frame(minHeight: 100) suffices. I included it just so it is clear what is going on.


    When the text is shorter than the image:

    enter image description here

    When the text is taller than the image:

    enter image description here