DEV Community

Budi Tanrim (buditanrim.co)
Budi Tanrim (buditanrim.co)

Posted on

How can I intercept the value from NSResponder and use that string? (SwiftUI)

Hi everyone, I need help with SwiftUI.
My goal: I have a macOS app built, and I want to...

  1. Have a button to open the emoji picker (managed this)
  2. When the user selects an emoji, intercept that value with NSResponder
  3. 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)
    }
}
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)