This content originally appeared on DEV Community and was authored by Budi Tanrim (buditanrim.co)
Hi everyone, I need help with SwiftUI.
My goal: I have a macOS app built, and I want to...
- Have a button to open the emoji picker (managed this)
- When the user selects an emoji, intercept that value with
NSResponder
- Then use it on my Button label
The code below is a simplification. I need help: How can I intercept the value from the NSResponder and print it?
import SwiftUI
import AppKit
struct ContentView: View {
private let emojiResponder = EmojiResponder()
var body: some View {
Button {
// open the emoji picker
if let window = NSApplication.shared.keyWindow {
window.makeFirstResponder(emojiResponder)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
NSApp.orderFrontCharacterPalette(nil)
}
}
} label: {
Text("Emoji?")
}
.onAppear {
emojiResponder.onEmojiSelected = { selectedEmoji in
print(selectedEmoji)
}
}
}
}
// Custom Emoji NSResponder
class EmojiResponder: NSResponder {
var onEmojiSelected: ((String) -> Void)?
// use insertTest method from NSResponder
// I assume this allows me to get the input
override func insertText(_ insertString: Any) {
guard let selectedEmoji = insertString as? String else { return }
onEmojiSelected?(selectedEmoji)
print(selectedEmoji)
}
}
Can anyone give me a pointer on how to solve this?
What happens now:
- The emoji picker is opened, but nothing happens after I select an emoji
This content originally appeared on DEV Community and was authored by Budi Tanrim (buditanrim.co)
Budi Tanrim (buditanrim.co) | Sciencx (2024-08-22T06:12:03+00:00) How can I intercept the value from NSResponder and use that string? (SwiftUI). Retrieved from https://www.scien.cx/2024/08/22/how-can-i-intercept-the-value-from-nsresponder-and-use-that-string-swiftui/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.