2

I want to have a Toggle with their content aligned to the right of the screen and I notice a Spacer doesn't work next to a Toggle inside a HStack:

import SwiftUI

struct ContentView: View {

    @State var isOn = false

    var body: some View {
        VStack { // with or without the VStack doesn't work.
            HStack {
                Spacer()
                Toggle(isOn: self.$isOn) {
                    Text("Remember me")
                }
            }
        }
    }
}

enter image description here

but if I put the Spacer and the Toggle inside a VStack it works (but vertically).

Also if a put another View instead the Toggle with the Spacer inside a HStack, it works.

How can I make it work the Spacer and the Toggle inside the HStack?

pableiros
  • 14,932
  • 12
  • 99
  • 105

1 Answers1

3

Are you using the Spacer to push the text to the right? If so, you could do this instead:

import SwiftUI

struct ContentView: View {

    @State var isOn = false

    var body: some View {
        VStack { // with or without the VStack doesn't work.
            HStack {
                Toggle(isOn: self.$isOn) {
                    Text("Remember me")
                        .frame(maxWidth: .infinity, alignment: .trailing)
                }
            }
        }
    }
}
Jobert
  • 1,532
  • 1
  • 13
  • 37