Detecting Focus on TextInput to Dispatch a Message

Hello Iced community,

I’m working on an application where I have several views with TextInput widgets, and I’d like to detect when they gain focus in order to dispatch a specific message. I’ve assigned an Id to my TextInput widgets like this:

let text_input = TextInput::new("", save_name)

I’ve looked into the find_focused operation, but I’m unsure how to proceed with it, or even if it’s the right tool for this job. I haven’t found a built-in on_focus event for TextInput. Could anyone guide me on how to properly use commands, or any other mechanism, to detect when a TextInput is focused and dispatch a message in response?

Any advice or examples would be greatly appreciated.

Thank you!

I was trying to achieve something similar a few months ago, and the solution I found was to create a very simple custom widget that wraps the iced::widget::TextInput widget and whose constructor allows passing a callback to receive messages for changes in the TextInput’s “focus state”.

Here’s the link to the repo: GitHub - BB-301/iced-text-input-wrapper-widget: A custom Iced widget that wraps around the official text input widget to allow subscribing to changes in the text input's focus state.

I have been struggling with the same question, determining which TextInput has the focus as I want to use up and down cursor keys to adjust the content of the field. It holds a String version of a date, so up and down increases and decreases the date. There are multiple ‘date’ fields on the screen. Your solution is really neat but seems a bit over engineered for what should be I feel a lot simpler. Anyway thanks for the answer, was useful for something else.

I maintain my own copy of the TextInput widget with added on_focus and on_unfocus event handlers. Feel free to use it in your app, it’s currently up to date with Iced 0.12.1: ~lufte/vimini (master): src/widget/ - sourcehut git.

Also read here on Hector’s response about including these handlers in the library: Support focus/unfocus events for TextInput and possibly other focusable widgets · iced-rs/iced · Discussion #2030 · GitHub.