Iced è la libreria grafica che userò per implementare interfacce grafiche in Rust.
Analizzando un’interfaccia, possiamo individuare tre concetti fondamentali:
Per un tutorial consulta: iced_tutorial.
Per creare un nuovo progetto con iced:
cargo new my_project
cd my_project
cargo add iced
Dentro cargo.toml dovremmo avere questa dipendeza:
[dependencies]
iced = "0.12.1"
Ora proviamo a creare un primo hello world:
use iced::{Sandbox, Settings};
fn main() -> iced::Result {
MyApp::run(Settings::default())
}
struct MyApp;
impl Sandbox for MyApp {
type Message = ();
fn new() -> Self {
Self
}
fn title(&self) -> String {
String::from("My App")
}
fn update(&mut self, _message: Self::Message) {}
fn view(&self) -> iced::Element<'_, Self::Message> {
"Hello World!".into()
}
}
Abbiamo fatto uso dell'oggetto Sandbox, ma come è strutturato?
use iced::{
widget::{button, column, row, text},
Sandbox, Settings,
};
fn main() -> iced::Result {
MyApp::run(Settings::default())
}
struct MyApp;
impl Sandbox for MyApp {
type Message = ();
fn new() -> Self {
Self
}
fn title(&self) -> String {
String::from("My App")
}
fn update(&mut self, _message: Self::Message) {}
fn view(&self) -> iced::Element<'_, Self::Message> {
column![
text("Yes or no?"),
row![
button("Yes"),
button("No"),
],
].into()
}
}
In questo modo creiamo una finestra con il testo "Yes or no?" e due pulsanti sotto.
Per modificare dinamicamente il contenuto in view, possiamo fare quanto segue:
counter) alla struttura principale MyApp.view (ad esempio text(self.counter)).view (ad esempio button(...).on_press(MyAppMessage::ButtonPressed)).update (ad esempio 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()
}
}