swiftswiftuihstackzstack

Is there a way to move HStack to leading?


I am having a problem with HStack which has bigger width than the parent view showing centre not leading.

struct WidgetEntryView : View {
    var entry: Provider.Entry
    
    var body: some View {
        ZStack {
            Color(.red)
            HStack {
                Text("haha1")
                    .frame(width: 50)
                Text("haha2")
                    .frame(width: 50)
                Text("haha3")
                    .frame(width: 50)
                Text("haha4")
                    .frame(width: 50)
                Text("haha5")
                    .frame(width: 50)
                Text("haha6")
                    .frame(width: 50)
                Text("haha7")
                    .frame(width: 50)
                Text("haha8")
                    .frame(width: 50)
            }
        }
    }
}

I'm creating a widget with some data on it. It's a medium size widget, and as you can see, HStack width gets bigger than Widget width, so it looks like below.

https://i.sstatic.net/uG4wO.png

Currently, anchor point of HStack is the centre, so it's showing from the centre, but I want to move it to leading so that it starts from haha1.

How can I achieve this?


Solution

  • struct WidgetEntryView : View {
        var entry: Provider.Entry
    
        var body: some View {
            ZStack {
                Color(.red)
                Color.clear
                    .overlay(
                        HStack {
                            Text("haha1")
                                .frame(width: 50)
                            Text("haha2")
                                .frame(width: 50)
                            Text("haha3")
                                .frame(width: 50)
                            Text("haha4")
                                .frame(width: 50)
                            Text("haha5")
                                .frame(width: 50)
                            Text("haha6")
                                .frame(width: 50)
                            Text("haha7")
                                .frame(width: 50)
                            Text("haha8")
                                .frame(width: 50)
                        }, alignment: .leading
                    )
    
            }
        }
    }
    

    did a trick.