Skip to content

Instantly share code, notes, and snippets.

@maiyama18
Created December 14, 2021 22:23
Show Gist options
  • Save maiyama18/f2e31ce7a44d8bbf88adc9f2ef85feea to your computer and use it in GitHub Desktop.
Save maiyama18/f2e31ce7a44d8bbf88adc9f2ef85feea to your computer and use it in GitHub Desktop.
import SwiftUI
struct ColoredButton {
let title: String
let color: Color
let offset: CGPoint
}
private let buttons = [
ColoredButton(title: "r\ned", color: .red, offset: CGPoint(x: -100, y: -200)),
ColoredButton(title: "bl\nue", color: .blue, offset: CGPoint(x: 100, y: 200)),
ColoredButton(title: "g\nr\ne\ne\nn", color: .green, offset: CGPoint(x: -100, y: 200)),
ColoredButton(title: "purple", color: .purple, offset: CGPoint(x: 100, y: -200)),
ColoredButton(title: "black", color: .black, offset: CGPoint(x: 0, y: 0)),
]
struct ContentView: View {
@Namespace private var ns
@State private var selectedIndex = 0
var body: some View {
ZStack(alignment: .center) {
ForEach(buttons.indices) { index in
Button(action: {
selectedIndex = index
}) {
Text(buttons[index].title)
.foregroundColor(buttons[index].color)
.padding(8)
}
.alignmentGuide(HorizontalAlignment.center) { d in d[HorizontalAlignment.center] - buttons[index].offset.x }
.alignmentGuide(VerticalAlignment.center) { d in d[VerticalAlignment.center] - buttons[index].offset.y }
.matchedGeometryEffect(id: index, in: ns, isSource: true)
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(.gray.opacity(0.3))
.overlay(
RoundedRectangle(cornerRadius: 8)
.stroke(lineWidth: 2)
.foregroundColor(buttons[selectedIndex].color)
.matchedGeometryEffect(id: selectedIndex, in: ns, isSource: false)
.animation(.easeInOut, value: selectedIndex)
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment