Home > other >  Toggle View doesn't behaves the same as other views in SwiftUI
Toggle View doesn't behaves the same as other views in SwiftUI

Time:09-30

I need the Toggle to align left as the top and bottom text. Can someone please explain why Toggle doesn't align left as the other two Text views.

struct GeneralTest: View {
    var body: some View {
        HStack(){
            VStack(alignment: .leading){
                Text("Some Text").font(.caption).foregroundColor(Color.blue)
                Toggle("", isOn: .constant(true))
                    .toggleStyle(SwitchToggleStyle(tint: Color.blue))
                Text("More Text").font(.caption).foregroundColor(Color.blue)
                
            }
            .frame(maxWidth:100)
        }
    }
}

What I'm seeing

enter image description here

CodePudding user response:

The space is there because SwiftUI is reserving that area for the toggle's title text. To hide it, do the following:

    struct GeneralTest: View {
    var body: some View {
        HStack(){
            VStack(alignment: .leading){
                Text("Some Text").font(.caption).foregroundColor(Color.blue)
                Toggle("", isOn: .constant(true))
                    .toggleStyle(SwitchToggleStyle(tint: Color.blue))
               // here, added labelsHidden
                .labelsHidden()
                Text("More Text").font(.caption).foregroundColor(Color.blue)
                
            }
            .frame(maxWidth:100)
        }
    }
}
  • Related