9

Code for Toggle in SwiftUI is this:

Toggle(isOn: $vibrateOnRing) {
    Text("Vibrate on Ring")
}

This will produce a toggle button with text label looking like this:

Vibrate on Ring | [--empty space--] | Toggle

I need a right-aligned text label, like this:

[--empty space--] | Vibrate on Ring | Toggle

How to do it in SwiftUI?

mallow
  • 2,368
  • 2
  • 22
  • 63

3 Answers3

21

Here it is

demo

Toggle(isOn: $vibrateOnRing) {
    Text("Vibrate on Ring")
      .frame(maxWidth: .infinity, alignment: .trailing)
}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Asperi
  • 228,894
  • 20
  • 464
  • 690
4

I was able to achieve this by decoupling the toggle button and the text label, that is:

HStack() {
    Spacer()
    Text("Vibrate on Ring")
    Toggle("", isOn: $vibrateOnRing).labelsHidden()
}

And for folks who are looking for a solution for center alignment, aka:

[--empty space--] | Vibrate on Ring | Toggle | [--empty space--]

simply add a trailing spacer:

HStack() {
    Spacer()
    Text("Vibrate on Ring")
    Toggle("", isOn: $vibrateOnRing).labelsHidden()
    Spacer()
}
pizza_time
  • 151
  • 8
0

This works for me

Toggle(isOn: $selPer, label: {
    HStack {
        Spacer()
        Image(systemName: "thermometer.sun")
            .foregroundColor(ITheme.IColor.sfImg)
            .font(.system(size: 12))
        if selPer {
            Text("关")
                .foregroundColor(Color.white)
                .font(ITheme.IFont.titleMin)
        } else {
            Text("开")
                .foregroundColor(Color.black)
                .font(ITheme.IFont.titleMin)
        }
    }
})
boblii
  • 1