Last active
September 4, 2023 08:51
-
-
Save StefKors/fa062893826d459dde27694cfbf8016e to your computer and use it in GitHub Desktop.
OnKeyPress needs focus, which makes it totally useless for global keyboard actions
This file contains hidden or 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
// | |
// ContentView.swift | |
// OnKeyPressIssue | |
// | |
// Created by Stef Kors on 04/09/2023. | |
// | |
import SwiftUI | |
struct ChildView: View { | |
@State private var text: String = "" | |
var body: some View { | |
TextField("field", text: $text) | |
} | |
} | |
struct FocusBlockingOnKeyPress: ViewModifier { | |
@FocusState private var focused: Bool | |
func body(content: Content) -> some View { | |
content | |
.focusable() | |
.focused($focused) | |
.focusEffectDisabled() | |
.onKeyPress { key in | |
print("pressed \(key.debugDescription)") | |
return .handled | |
} | |
.onAppear { | |
focused = true | |
} | |
} | |
} | |
struct ContentView: View { | |
var body: some View { | |
VStack { | |
Image(systemName: "globe") | |
.imageScale(.large) | |
.foregroundStyle(.tint) | |
Text("Hello, world!") | |
ChildView() | |
} | |
.padding() | |
.modifier(FocusBlockingOnKeyPress()) | |
} | |
} | |
#Preview { | |
ContentView() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Screen.Recording.2023-09-04.at.10.46.59.mov