1
votes

I want to display a label in the centre of a view with a progress indicator to the right of the label. How can I do this in SwiftUI on macOS?

The code below aligns the HStack in the centre of the VStack but I want the text centered and the progress indicator aligned with the text's trailing edge. I guess I could replace the HStack with a ZStack but it's still not clear how one aligns two controls to each other or how one prevents the container from be centered by its container.

import SwiftUI

struct AlignmentTestView: View {
    var body: some View {
        VStack(alignment: .center, spacing: 4) {
            HStack {
                Text("Some text")
                ActivityIndicator()
            }
        }.frame(width: 200, height: 200)
            .background(Color.pink)
    }
}

struct AlignmentTestView_Previews: PreviewProvider {
    static var previews: some View {
        AlignmentTestView()
    }
}
1

1 Answers

0
votes

Here is possible approach (tested replacing ActivityIndicator with just circle).

Used Xcode 11.4 / iOS 13.4 / macOS 10.15.4

demo

demo

var body: some View {
    VStack {
        HStack {
            Text("Some text")
                .alignmentGuide(.hAlignment) { $0.width / 2.0 }
            ActivityIndicator()
        }
    }
    .frame(width: 200, height: 200, alignment: 
           Alignment(horizontal: .hAlignment, vertical: VerticalAlignment.center))
    .background(Color.pink)
}

extension HorizontalAlignment {
    private enum HAlignment : AlignmentID {
        static func defaultValue(in d: ViewDimensions) -> CGFloat {
            return d[HorizontalAlignment.center]
        }
    }

    static let hAlignment = HorizontalAlignment(HAlignment.self)
}