Lalli
Lalli

Reputation: 466

How to change radius of segmented control in swiftUI without using old UISegmentControl

I was trying to change radius of segment control in SwiftUI. I am only able to change the outer radius. Is there any way to change the radius of selected tag?

struct ContentView: View {
    @State private var favoriteColor = 0
    var colors = ["Red", "Green", "Blue"]

    var body: some View {
        VStack {
            Picker(selection: $favoriteColor, label: Text("What is your favorite color?")) {
                ForEach(0..<colors.count) { index in
                    Text(self.colors[index]).tag(index)
                }
            }.pickerStyle(SegmentedPickerStyle())
             .cornerRadius(13). ////////////////////////////////--

            Text("Value: \(colors[favoriteColor])")
        }
    }
}

Upvotes: 5

Views: 2216

Answers (2)

AnupamChugh
AnupamChugh

Reputation: 1909

Use the Introspection Library to access the underlying UISegmentedControl from the SwiftUI view. Doing so, you can customize it. Here's an example for you:

struct ContentView : View {
    // 1.
    @State private var selectorIndex = 0
    @State private var numbers = ["One","Two","Three"]

    var body: some View {
        VStack {
            // 2
            Picker("Numbers", selection: $selectorIndex) {
                ForEach(0 ..< numbers.count) { index in
                    Text(self.numbers[index]).tag(index)
                }
            }
            .pickerStyle(SegmentedPickerStyle())
            .introspectSegmentedControl{
                segmentedControl in

                segmentedControl.layer.cornerRadius = 0
                segmentedControl.layer.borderColor = UIColor(red: 170.0/255.0, green: 170.0/255.0, blue: 170.0/255.0, alpha: 1.0).cgColor
                segmentedControl.layer.borderWidth = 1.0
                segmentedControl.layer.masksToBounds = true
                segmentedControl.clipsToBounds = true
            }

            // 3.
            Text("Selected value is: \(numbers[selectorIndex])").padding()
        }
    }
}

Upvotes: 3

John M.
John M.

Reputation: 9473

At this point, I believe there is no way to modify the properties (e.g. shape) of the selected tag. I assume this is either a stylistic choice by Apple (because they want standard controls to truly look "standard"), or they just haven't gotten around to it (SwiftUI is very much a 1.0 at this point).

Upvotes: 3

Related Questions