Skip to content

Latest commit

 

History

History
76 lines (62 loc) · 3.01 KB

controlling_widgets_by_commands.md

File metadata and controls

76 lines (62 loc) · 3.01 KB

Controlling Widgets By Commands

We can use Command to control widgets. Some widgets have functions to change their behavior. These functions are located at their respective modules. For example, focus is a function in text_input module that makes a TextInput gaining the focus. This function takes a parameter text_input::Id, which can be specified by id method of TextInput. The function returns a Command and we can return the Command in update or new methods of Application.

use iced::{
    executor,
    widget::{button, column, text_input},
    Application, Command, Settings,
};

fn main() -> iced::Result {
    MyApp::run(Settings::default())
}

const MY_TEXT_ID: &str = "my_text";

#[derive(Debug, Clone)]
enum MyAppMessage {
    EditText,
    UpdateText(String),
}

struct MyApp {
    some_text: String,
}

impl Application for MyApp {
    type Executor = executor::Default;
    type Message = MyAppMessage;
    type Theme = iced::Theme;
    type Flags = ();

    fn new(_flags: Self::Flags) -> (Self, iced::Command<Self::Message>) {
        (
            Self {
                some_text: String::new(),
            },
            Command::none(),
        )
    }

    fn title(&self) -> String {
        String::from("My App")
    }

    fn update(&mut self, message: Self::Message) -> iced::Command<Self::Message> {
        match message {
            MyAppMessage::EditText => return text_input::focus(text_input::Id::new(MY_TEXT_ID)),
            MyAppMessage::UpdateText(s) => self.some_text = s,
        }
        Command::none()
    }

    fn view(&self) -> iced::Element<Self::Message> {
        column![
            button("Edit text").on_press(MyAppMessage::EditText),
            text_input("", &self.some_text)
                .id(text_input::Id::new(MY_TEXT_ID))
                .on_input(MyAppMessage::UpdateText),
        ]
        .into()
    }
}

Controlling widgets by commands

➡️ Next: Batch Commands

📘 Back: Table of contents