Home > database >  SwiftUI Align VStack Top Leading in ZStack
SwiftUI Align VStack Top Leading in ZStack

Time:12-20

I have a Stack I am using to create a graph with 2 different lines, but I also want to have 2 labels on the graph. I want these labels to be in the top left of the ZStack but cannot figure out how. Here's what I've tried:

    ZStack {
        
        ZStack(alignment: .topLeading) {
            VStack {
                Text("Contributions")
                    .frame(width: 180, height: textHeight, alignment: .center)
                    .background(Color.POI.blue)
                    .cornerRadius(textHeight / 2)
                    .multilineTextAlignment(.center)

                Text("Earnings")
                    .frame(width: 150, alignment: .center)
                    .cornerRadius(dimensions.cornerRadiusLarge)
                    .multilineTextAlignment(.center)
            }
        }
    // Rest of the graph
  }

CodePudding user response:

 HStack {
        ZStack(alignment: .topLeading) {
                    VStack {
                        Text("Contributions")
                            .frame(width: 180, height: textHeight, alignment: .center)
                            .background(Color.POI.blue)
                            .cornerRadius(textHeight / 2)
                        Text("Earnings")
                            .frame(width: 150, alignment: .center)
                            .cornerRadius(dimensions.cornerRadiusLarge)
                        Spacer()
                    }
                .multilineTextAlignment(.center)
            }
        // Rest of the graph
        Spacer()
      }

CodePudding user response:

In swiftUI the View size depends on its child. In you case the 2 text are not pushing the Zstack to whole view of screen. For this purpose we need add view that cover all the space of screen e.g(Color, Rectangle, Circle) and then your required alignment will work.

enter image description here

Have a look at this code, You code is also perfect but your Zstack is not expanding to the size of screen. I just add a view that push your Zstack and your alignment will start working.

struct ContentView: View {
    
    var textHeight = 100.0
    
    var body: some View {
        
        ZStack(alignment: .topLeading) {
            Color.yellow
            
            VStack {
                Text("Contributions")
                    .frame(width: 180, height: textHeight, alignment: .center)
                    .background(.blue)
                    .cornerRadius(textHeight / 2)
                    .multilineTextAlignment(.center)
                
                Text("Earnings")
                    .frame(width: 150, alignment: .center)
                    .cornerRadius(20)
                    .multilineTextAlignment(.center)
            }
        }
        
        
    }
}
  • Related