'Position view relative to a another centered view

Hello SwiftUI community,

I'm trying to do something that's probably easy to do but I'm stuck on it since hours. In a list, I'd like to have items composed of:

  • A text centered horizontaly (a number)
  • A text on the left of the number
  • A text on the right of the number

enter image description here

I've tried many things (alignments, aligmentguides, GeometryReader....) but didn't find the way to achieve the result above. Does anyone has an example to help me?

Thanks 🙏🏻



Solution 1:[1]

Here is possible solution. Tested with Xcode 11.4 / iOS 13.4

demo

A view for List row

struct DemoCenteredNumberView: View {
    var value: Int
    var body: some View {
        HStack {
            Spacer().overlay(
                Text("Text on left side")
                    .frame(maxWidth: .infinity, alignment: .trailing)
            )
            Text("\(value)").padding()
            Spacer().overlay(
                Text("Text on right")
                    .frame(maxWidth: .infinity, alignment: .leading)
            )
        }
    }
}

backup

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1