Skip to content

Instantly share code, notes, and snippets.

@sturdysturge
Created July 20, 2020 21:24
Show Gist options
  • Save sturdysturge/47be3a9d065102a213b56264d1757937 to your computer and use it in GitHub Desktop.
Save sturdysturge/47be3a9d065102a213b56264d1757937 to your computer and use it in GitHub Desktop.
RevDoc matchedGeometryEffect
import SwiftUI
struct MatchedTextView: View {
let namespace: Namespace.ID
let colour: Color
var body: some View {
Text("Tap to move!")
.fontWeight(.semibold)
.foregroundColor(colour)
.matchedGeometryEffect(id: "text", in: namespace)
}
}
struct MatchedRoundedView: View {
let namespace: Namespace.ID
let colour: Color
let isCentre: Bool
var body: some View {
Circle()
.foregroundColor(colour)
.opacity(isCentre ? 0.5 : 1)
.frame(width: 60, height: 60)
.matchedGeometryEffect(id: "rect", in: namespace)
}
}
struct MatchedGeometryEffectView: View {
@State private var position: TextPosition = .bottom
@Namespace private var namespace
var body: some View {
Group {
switch position {
case .bottom:
VStack {
MatchedRoundedView(namespace: namespace, colour: position.colour, isCentre: position == .centre)
MatchedTextView(namespace: namespace, colour: position.colour)
}
case .left:
HStack {
MatchedTextView(namespace: namespace, colour: position.colour)
MatchedRoundedView(namespace: namespace, colour: position.colour, isCentre: position == .centre)
}
case .centre:
ZStack {
MatchedRoundedView(namespace: namespace, colour: position.colour, isCentre: position == .centre)
MatchedTextView(namespace: namespace, colour: position.colour)
}
case .right:
HStack {
MatchedRoundedView(namespace: namespace, colour: position.colour, isCentre: position == .centre)
MatchedTextView(namespace: namespace, colour: position.colour)
}
case .top:
VStack {
MatchedTextView(namespace: namespace, colour: position.colour)
MatchedRoundedView(namespace: namespace, colour: position.colour, isCentre: position == .centre)
}
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.primary.colorInvert())
.onTapGesture {
withAnimation {
position.next()
}
}
}
}
enum TextPosition: CaseIterable {
case bottom, left, centre, right, top
var colour: Color {
switch self {
case .bottom:
return .orange
case .left:
return .red
case .centre:
return .green
case .right:
return .blue
case .top:
return .purple
}
}
mutating func next() {
var index = 0
while TextPosition.allCases[index] != self { index += 1 }
if TextPosition.allCases.indices.contains(index + 1) {
self = TextPosition.allCases[index + 1]
}
else {
self = TextPosition.allCases[0]
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment