garysimpson.dev
Mobile development with swift and flutter

SwiftUI CheckBox

March 14, 2023 at 1:30PM

Nothing too fancy here. Why isnt there a native solution?

struct CheckboxUIView: View {
    let title: String
    let tooltip: String
    @State var isChecked: Bool
    @State var isHovering: Bool = false
    let action: (()->Void)?
    
    var body: some View {
        Button(action: { self.isChecked.toggle(); action?() }) {
            HStack(spacing: 8) {
                Text(title).foregroundColor(Color.primary)
                    .lineLimit(1)
                    .frame(maxWidth: 96)
                Image(systemName: isChecked ? "checkmark.rectangle" : "rectangle")
                    .frame(width: 32, height: 32)
            }
            .frame(height: 32)
            .frame(maxWidth: .infinity, maxHeight: .infinity) //Full height/width MUST COME BEFORE SHAPE
            .contentShape(Rectangle()) // This makes the whole button area clickable
        }
        .help(tooltip)
        .foregroundColor(isChecked ? NSColor.controlAccentColor.toColor : .primary)
        .background(isHovering ? Color(NSColor.quaternaryLabelColor) : Color.clear)
        .buttonStyle(PlainButtonStyle())
        .cornerRadius(7) // Apply corner radius to the background
        .clipped() // Clip the view to the corner radius
        
        .onHover(perform: { hovering in
            isHovering = hovering
        })
    }
}


Happy Coding ;-)