Skip to content

Instantly share code, notes, and snippets.

@kwylez
Created October 5, 2022 03:47
Show Gist options
  • Save kwylez/845ad7110e4b11aa57453ad443ed4e5b to your computer and use it in GitHub Desktop.
Save kwylez/845ad7110e4b11aa57453ad443ed4e5b to your computer and use it in GitHub Desktop.
struct CustomSegmentControl: View {
@Binding
var selection: String
private var labels: Array<String> {
return [
"Precautions",
"Prework",
"Hazards"
]
}
var body: some View {
HStack {
ForEach(labels, id: \.self){label in
Button(action: {
selection = label
}) {
Text(label)
.font(.subheadline.weight(.semibold))
.foregroundColor(selection == label ? .secondary : .white)
.padding()
}
.anchorPreference(key: SegmentControlPreferenceKey.self,
value: .bounds,
transform: { [
SegmentControlPreference(
menuLabel: label,
anchor: $0
)
]}
)
}
}
.padding(.vertical)
.frame(minWidth: 0, maxWidth: .infinity)
.backgroundPreferenceValue(SegmentControlPreferenceKey.self) { preferences in
GeometryReader { proxy in
if let selected = preferences.first(where: { $0.menuLabel == selection }) {
let frame = proxy[selected.anchor]
SegmentControlBackground()
.frame(width: frame.width)
.frame(height: frame.height)
.position(x: frame.midX, y: frame.midY)
.animation(.interpolatingSpring(stiffness: 170, damping: 15).delay(0.05), value: selection)
}
}
}
.background(
Capsule()
.foregroundColor(.secondary)
.blendMode(.multiply)
)
.padding(.horizontal)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment