swiftbuttonswiftuifigma

Is there a way to create a Two-Side Button in SwiftUI?


I hope you're all doing well here. I'm working on developing my first app, and I've created a two-sided button in Figma using a rectangle. I really like the design, and I was wondering if there's a way to recreate it in SwiftUI. As you can see, when I press either "Lyrics" or "Chords," a small "-" should appear below the selected word to indicate which section I'm currently in.

Image

I couldn't actually create the button the way I wanted it to be. I've been struggling with it and couldn't figure out how to make it work.

Basically, what I'm trying to do is create a cool two-sided button in SwiftUI, just like the one I made in Figma.


Solution

  • try this approach using a Picker with .pickerStyle(.segmented). Adjust the looks of it as you see fit.

    struct ContentView: View {
        @State var selection = 0
        var body: some View {
            Picker("", selection: $selection) {
                Text("Lyrics").tag(0)
                Text("Chords").tag(1)
            }
            .pickerStyle(.segmented)
            .overlay(RoundedRectangle(cornerRadius: 15)
                        .stroke(Color.gray, lineWidth: 2)
                )
            .frame(width: 234)
        }
    }
    

    You could also use two Buttons in a HStack, such as:

    struct ContentView: View {
        @State var selection = 0
        var body: some View {
            HStack {
                Button(action: {selection = 0}) {
                    Text("Lyrics").underline(selection == 0)
                }
                Divider()
                Button(action: {selection = 1}) {
                    Text("Chords").underline(selection == 1)
                }
            }.frame(width: 160, height: 33)
                .overlay(RoundedRectangle(cornerRadius: 15).stroke(Color.gray, lineWidth: 2))
                .frame(width: 160)
        }
    }