Skip to content

Instantly share code, notes, and snippets.

@sturdysturge
Last active July 17, 2020 14:59
Show Gist options
  • Save sturdysturge/85656f0874a0c0780fc1593e8f56562e to your computer and use it in GitHub Desktop.
Save sturdysturge/85656f0874a0c0780fc1593e8f56562e to your computer and use it in GitHub Desktop.
RevDoc TV onLongPressGesture
import SwiftUI
enum ButtonState: String {
case unfocused, focused, pressing, pressed
var colour: Color {
switch self {
case .unfocused:
return .white
case .focused:
return .red
case .pressing:
return .orange
case .pressed:
return .green
}
}
}
struct ContentView: View {
@State var selectedIndex = 0
var body: some View {
VStack {
CustomButton(index: 0, currentIndex: $selectedIndex)
CustomButton(index: 1, currentIndex: $selectedIndex)
}
}
}
struct CustomButton: View {
let index: Int
@Binding var currentIndex: Int
@State var buttonState = ButtonState.unfocused
var isFocused: Bool {
return index == currentIndex
}
var focusedState: ButtonState {
return isFocused ? .focused : .unfocused
}
var body: some View {
Text(buttonState.rawValue)
.foregroundColor(.black)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(buttonState.colour)
.focusable(true) {
focused in if focused { currentIndex = index }
buttonState = focusedState
}
.onChange(of: currentIndex) {
currentIndex in buttonState = focusedState
}
.onLongPressGesture(minimumDuration: 2, pressing: { pressing in
buttonState = pressing ? .pressing : .focused
}) {
buttonState = .pressed
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment