Search code examples
swiftswiftuitoggleusability

SwiftUI - how to increase Toggle's target touch size?


I want to increase Toggle's target size for usability purposes. It's easy with buttons using .frame(width: 200, height: 200) . But I don't know how to apply the same for toggles.

Here is my code. I have marked where it works and where it doesn't.

import SwiftUI

struct ContentView: View {
    
    @State private var test = true
    
    var body: some View {
        VStack {
            Text("Hello, world!")
                .padding()
            
            Button(action: {
                print("button pressed")
            }) {
                Image(systemName: "checkmark.circle.fill")
                    .font(.largeTitle)
                    // This works for Button
                    .frame(width: 200, height: 200)
            }
            
            Toggle(isOn: Binding<Bool>(
                    get: { test },
                    set: {
                        test = $0
                    })) {
                Text("Done")
            }
            // This doesn't work for Toggle
            .frame(width: 200, height: 200)
            .labelsHidden()
        }
        
        
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Solution

  • You can try something like this:

            Toggle(isOn: Binding<Bool>(
                    get: { test },
                    set: {
                        test = $0
                    })) {
                Text("Done")
            }
            .frame(width: 200, height: 200)
            .labelsHidden()
            .contentShape(Rectangle())
            .onTapGesture {
                    withAnimation {
                       test.toggle()
                    }
            }