iosswiftswiftuiviewmodifier

Can I support `labelsHidden` modifier in custom view/style?


I have a custom Toggle style but it doesn't work with labelsHidden() view modifier. Is it possible to support it? I know that I can add a property to my style or hide it right in the body, but I wondering if I can support exactly this modifier


Solution

  • You can use LabeledContent in your custom ToggleStyle. When you call labelsHidden() modifier, label will not be visible:

    struct CustomToggleStyle: ToggleStyle {
        func makeBody(configuration: Configuration) -> some View {
            LabeledContent(
                content: {
                    ZStack {
                        Capsule()
                            .fill(.gray)
                            .frame(width: 64, height: 32)
                        Circle()
                            .fill(configuration.isOn ? .green : .white)
                            .frame(width: 24, height: 24)
                            .animation(.bouncy, value: configuration.isOn)
                            .offset(x: configuration.isOn ? 16 : -16)
                    }
                    .onTapGesture {
                        configuration.isOn.toggle()
                    }
                }, label: {
                    configuration.label
                }
            )
        }
    }
    
    Toggle("Toggle", isOn: $isOn)
       .toggleStyle(CustomToggleStyle())
       .labelsHidden()