Skip to content

Instantly share code, notes, and snippets.

@JadenGeller
Last active October 26, 2023 23:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JadenGeller/277954380b52ff0ba9d9c7a42a86df2f to your computer and use it in GitHub Desktop.
Save JadenGeller/277954380b52ff0ba9d9c7a42a86df2f to your computer and use it in GitHub Desktop.
SwiftUI bug! onKeyPress resets binding to initial state
import SwiftUI
struct OuterView: View {
@State var count: Int = 0
var body: some View {
VStack {
MiddleView(count: $count)
.onAppear {
count += 100
}
}
}
}
struct MiddleView: View {
@Binding var count: Int
var body: some View {
InnerView(count: $count)
.focusable()
.onKeyPress(.space) {
count += 1 // will evaluate to 0 during first execution even after count has already been updated
return .handled
}
.onTapGesture {
count += 1
}
}
}
struct InnerView: View {
@Binding var count: Int
var body: some View {
Text(String(count))
}
}
@JadenGeller
Copy link
Author

If you tap the number, the count will increase from 100. If you press space, the count will increase from 0. Things behave as expected after a keypress handler has run at least once.

@JadenGeller
Copy link
Author

FB13303824

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment