Skip to content

Instantly share code, notes, and snippets.

@StefKors
Last active September 4, 2023 08:51
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 StefKors/fa062893826d459dde27694cfbf8016e to your computer and use it in GitHub Desktop.
Save StefKors/fa062893826d459dde27694cfbf8016e to your computer and use it in GitHub Desktop.
OnKeyPress needs focus, which makes it totally useless for global keyboard actions
//
// 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()
}
@StefKors
Copy link
Author

StefKors commented Sep 4, 2023

Screen.Recording.2023-09-04.at.10.46.59.mov

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