Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove or hide the label of a Toggle in SwiftUI

Tags:

ios

swift

swiftui

I'm looking for a way to remove the label of a Toggle in SwiftUI...

I have tried with ToggleStyle but it does not seems to be the right way:

Toggle(isOn: $isBlinky) {
    Text("DO NOT DISPLAY").color(.red)
}
.toggleStyle(.switch)

As the label seems to be included in the type itself (struct Toggle<Label>) there may be no way to only have the switch alone...

By the way if I use Text("") and then scaledToFit() the switch is still a bit on the right and not really centered...

Anyway if someone has an idea!

PS: While waiting for a solution, I wrapped a good old UISwitch, but that's not the idea...

struct Switch : UIViewRepresentable {
    @Binding var isOn : Bool

    func makeUIView(context: Context) -> UISwitch {
        let uiView = UISwitch()
        uiView.addTarget(
            context.coordinator,
            action: #selector(Coordinator.didChange(sender:)),
            for: .valueChanged)

        return uiView
    }

    func updateUIView(_ uiView: UISwitch, context: Context) {
        uiView.isOn = isOn
    }

    // MARK:- Coordinator

    func makeCoordinator() -> Switch.Coordinator {
        return Coordinator(self)
    }

    class Coordinator: NSObject {
        var control: Switch

        init(_ control: Switch) {
            self.control = control
        }

        @objc func didChange(sender: UISwitch) {
            control.isOn = sender.isOn
        }
    }
}
like image 430
Zaphod Avatar asked Jun 28 '19 09:06

Zaphod


2 Answers

SwiftUI 1.0

Hide the label/title with the labelsHidden Modifier

This is how it should be done.

Toggle("Turn alarm on", isOn: $isToggleOn)
    .labelsHidden() // Hides the label/title

Note: Even though the label is hidden, you should still add one for accessibility purposes.

Example:

Toggle Example with no Label

like image 58
Mark Moeykens Avatar answered Nov 03 '22 12:11

Mark Moeykens


You can hide label with the .labelsHidden() modifier:

Toggle(isOn: $switchValue) {}
      .labelsHidden()
like image 42
caglar Avatar answered Nov 03 '22 10:11

caglar