skip to Main Content

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")
           }

        }

4

Answers


  1. Try adding alignment: .leading to the VStack:

    VStack(alignment: .leading) {
        HStack {
            Text("Text")
            Toggle(isOn: binding) {
                Text("Hello World")
            }.padding()
        }
        Text("Final Context")
    }
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
  3. 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")
                  }
            }
         }
      }
    
    Login or Signup to reply.
  4. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search