Last active
October 26, 2023 23:57
-
-
Save JadenGeller/277954380b52ff0ba9d9c7a42a86df2f to your computer and use it in GitHub Desktop.
SwiftUI bug! onKeyPress resets binding to initial state
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.