Home > Blockchain >  How do I get segment style button in SwiftUI
How do I get segment style button in SwiftUI

Time:02-07

So in SwiftUI, macOS, I want individual buttons that can be turned on and off like check boxes but look like buttons, and they are interrelates, think like bit flags, and so I want them to touch like you can with NSSegmentedControl, it would seem to me you want use Button or Toggle with some modifier to group them, but I can't find it, PickerStyle seems to be exclusively radio options, which makes sense as SwiftUI seems to be more about describing the function, and then controlling how that is presented.

Update to make it clearer

It for regular expression options, I could do it with checkbox, but it doesn't look very good, it feels like there should be a method to change how the checkboxes are displayed, in this example I have the first three buttons enabled. enter image description here

CodePudding user response:

here is a simple custom solution:

struct Option: Hashable {
    let label: String
    var selected: Bool
}


struct ContentView: View {
    
    @State var options: [Option] = [
        Option(label: "Dot All", selected: false),
        Option(label: "Extended", selected: false),
        Option(label: "Ignore Case", selected: false),
        Option(label: "Multi-line", selected: false),
    ]
    
    var body: some View {
        OptionPicker(options: $options)
    }
}


struct OptionPicker: View {
    
    @Binding var options: [Option]
    
    var body: some View {
        HStack(spacing: 0) {
            ForEach(options.indices, id: \.self) { i in
                
                Text(options[i].label)
                    .padding(.horizontal, 4)
                    .padding(5)
                    .background(options[i].selected ? .blue : .gray)
                
                    .onTapGesture {
                        options[i].selected.toggle()
                    }
                
                if i < options.count-1 {
                Divider()
                }
            }
        }
        .foregroundColor(.white)
        .cornerRadius(10)
        .frame(height: 32)
    }
}

enter image description here

  •  Tags:  
  • Related