Home > database >  SwiftUI: How to center align independent of other content in HStack?
SwiftUI: How to center align independent of other content in HStack?

Time:11-28

I have an HStack with content I want left aligned and then Details title to be centered. I am using a Spacer() to try and accomplish this but it looks like it's centering Details dependent on the content to the left of it. I would like it to be independent of that and just be centered to the screen. Is that possible using Spacer()?

enter image description here

    VStack {
        HStack(alignment: .top) {
            Text("<------")
            Spacer()
            Text("Details")
            Spacer()
        }
        Spacer()         
    }

CodePudding user response:

A possible approach is to use overlay, like

VStack {
    HStack(alignment: .top) {
        Text("<------")
        Spacer()
    }
    .overlay(
        Text("Details")       // << here !!
    , alignment: .top)
    Spacer()         
}

, depending on needs you can place it to root VStack

  • Related