Home > Software design >  How to align an element in case of multiple elements in SwiftUI?
How to align an element in case of multiple elements in SwiftUI?

Time:05-16

I am trying to alight my text Final Context below Hello World and after Text1 but I am unable to do so, here is my code. I am new to SwiftUI.

    
           VStack {
               HStack{
                   Text("Text1")
                   Toggle(isOn: binding){
                    Text("Hello World")
                   }.padding()
               }
               Text("Final Context")
           }

        }

CodePudding user response:

What about this:

 struct align: View {
     @State private var binding = false
     var body: some View {
        HStack(alignment: .top){
              VStack{
                 Text("Text")
              }
              .padding(.top, 5)
              
              VStack(alignment: .leading){
                 
                 Toggle(isOn: $binding){
                    Text("Hello World")
                 }
                 
                 Text("Final Context")
              }
        }
     }
  }

CodePudding user response:

Try adding alignment: .leading to the VStack:

VStack(alignment: .leading) {
    HStack {
        Text("Text")
        Toggle(isOn: binding) {
            Text("Hello World")
        }.padding()
    }
    Text("Final Context")
}

CodePudding user response:

You have to align your vStack to leading. Your code should look like this: import SwiftUI

struct ContentView: View {
    
    @State private var binding = false
    
    var body: some View {
        VStack(alignment: .leading) {
           HStack{
               Text("Text")
               Toggle(isOn: $binding){
                Text("Hello World")
               }.padding()
           }
           Text("Final Context")
       }
    }
}

Then you get the alignment, like this:

enter image description here

CodePudding user response:

Use a VStack inside HStack.

var body: some View {
    VStack {
      HStack{
        Text("Text")
        VStack(alignment:.leading){
          Toggle(isOn: $toggle){
            Text("Hello World")
          }
          Text("Final Context")
        }
      }
    }
  }

enter image description here

  • Related