Skip to content

Latest commit

 

History

History
92 lines (77 loc) · 3.21 KB

changing_the_window_dynamically.md

File metadata and controls

92 lines (77 loc) · 3.21 KB

Changing The Window Dynamically

We can use functions provided in window module to change the window after it is initialized. For example, to resize the window. These functions return Command, which can be used as the return value in update method. Developers might be interested in other Commands in window module.

The resize function needs an ID of the window we are going to resize. Internally, Iced reserves window::Id::MAIN for the first window spawned.

use iced::{
    widget::{button, row, text_input},
    window, Element, Size, Task,
};

fn main() -> iced::Result {
    iced::application(
        "changing the window dynamically",
        MyApp::update,
        MyApp::view,
    )
    .run()
}

struct MyApp {
    width: String,
    height: String,
}

impl Default for MyApp {
    fn default() -> Self {
        MyApp::new().0
    }
}

#[derive(Debug, Clone)]
enum Message {
    UpdateWidth(String),
    UpdateHeight(String),
    ResizeWindow,
}
  
impl MyApp {
    fn new() -> (Self, Task<Message>) {
        (
            Self {
                width: String::new(),
                height: String::new(),
            },
            Task::none(),
        )
    }
  
    fn update(&mut self, message: Message) -> Task<Message> {
        match message {
            Message::UpdateWidth(w) => {
                self.width = w;
            }
            Message::UpdateHeight(h) => {
                self.height = h;
            }

            Message::ResizeWindow => {
                // If don't define var "width" and "height", error 'E0521' will occur.
                let width = self.width.parse().unwrap();
                let height = self.height.parse().unwrap();
  
                // Id in Task<Option<Id>> will be delivered to Task::and_then() method, then to the closure.
                return window::get_oldest()
                    .and_then(move |window| window::resize(window, Size::new(width, height)));
            }
        }
        Task::none()
    }
  
    fn view(&self) -> Element<Message> {
        row!(
            text_input("Width", &self.width).on_input(Message::UpdateWidth),
            text_input("Height", &self.height).on_input(Message::UpdateHeight),
            button("Resize window").on_press(Message::ResizeWindow),
        )
        .into()
    }
}

Changing the window dynamically

➡️ Next: Closing The Window On Demand

📘 Back: Table of contents