To change the content in view dynamically, we can do the following:
- Add some fields (e.g.,
counter
) to the main structMyApp
. - Display the fields in view (e.g.,
text(self.counter)
). - Produce some messages in view (e.g.,
button(...).on_press(MyAppMessage::ButtonPressed)
). - Update the fields when messages are received in update (e.g.,
self.counter += 1
).
use iced::{
widget::{button, column, text},
Sandbox, Settings,
};
fn main() -> iced::Result {
MyApp::run(Settings::default())
}
#[derive(Debug, Clone)]
enum MyAppMessage {
ButtonPressed,
}
struct MyApp {
counter: usize,
}
impl Sandbox for MyApp {
type Message = MyAppMessage;
fn new() -> Self {
Self { counter: 0 }
}
fn title(&self) -> String {
String::from("My App")
}
fn update(&mut self, message: Self::Message) {
match message {
MyAppMessage::ButtonPressed => self.counter += 1,
}
}
fn view(&self) -> iced::Element<Self::Message> {
column![
text(self.counter),
button("Increase").on_press(MyAppMessage::ButtonPressed),
]
.into()
}
}
➡️ Next: Text
📘 Back: Table of contents