Search code examples
iosswiftswiftuiautolayouthstack

How to alternate centerX auto layout constraint in SwiftUI


I want to adjust my view like this to make an element align horizontally center of its parent and lead another view to that.

This is what I want to implement with SwiftUI

I implement this view with auto layout simply like this.

consumeLabel.centerXAnchor.constraint(equalTo: parentView.centerXAnchor).isActive = true
unitLabel.leadingAnchor.constraint(equalTo: consumeLabel.trailingAnchor, constant: 5).isActive = true

But I couldn't find out how can I implement this by SwiftUI.

This is what I'm trying:

ZStack {
        Image("waterHomeHeader")
            .resizable()
            .scaledToFill()
            .edgesIgnoringSafeArea(.all)
        HStack {
            Text("1350 / 2917")
                .frame(alignment: .center)
                .foregroundColor(.white)
                .font(.title2)
            Text("ml")
                .foregroundColor(.white)
                .font(.footnote)
                .padding(.leading, 2)
        }
    }

Solution

  • Here is possible solution (tested with Xcode 12.1 / iOS 14.1)

        HStack {
            Spacer()
            Text("1350 / 2917")
                .frame(alignment: .center)
                .foregroundColor(.white)
                .font(.title2)
            Spacer().overlay(
                Text("ml")
                    .foregroundColor(.white)
                    .font(.footnote)
                    .padding(.leading, 2), alignment: .leading)
        }