We mentioned in the previous tutorial about how to change styles of widgets by the enums in theme module.
Most enums in theme module support Custom
variant, e.g., theme::Radio::Custom(...).
This variant takes radio::StyleSheet trait as its parameter.
To use the variant, we need to implement the trait (such as RadioStyle
struct in the following code).
The associated type of the trait should be set to iced::Theme.
The methods in the trait return radio::Appearance.
We can use theme::Radio::Default to obtain the default value of radio::Appearance, e.g., style.active(&theme::Radio::Default, is_selected)
.
After that, we can modify the default radio::Appearance based on our needs.
use iced::{
theme,
widget::{column, radio},
Color, Sandbox, Settings,
};
fn main() -> iced::Result {
MyApp::run(Settings::default())
}
#[derive(Debug, Clone)]
enum MyAppMessage {
Choose(String),
}
struct MyApp;
impl Sandbox for MyApp {
type Message = MyAppMessage;
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![
radio("Choice A", "A", Some("A"), |s| MyAppMessage::Choose(
s.to_string()
))
.style(theme::Radio::Custom(Box::new(RadioStyle))),
radio("Choice B", "B", Some("A"), |s| MyAppMessage::Choose(
s.to_string()
))
.style(theme::Radio::Custom(Box::new(RadioStyle))),
radio("Choice C", "C", Some("A"), |s| MyAppMessage::Choose(
s.to_string()
)),
]
.into()
}
}
struct RadioStyle;
impl radio::StyleSheet for RadioStyle {
type Style = iced::Theme;
fn active(&self, style: &Self::Style, is_selected: bool) -> radio::Appearance {
radio::Appearance {
text_color: Some(if is_selected {
Color::from_rgb(0., 0., 1.)
} else {
Color::from_rgb(0.5, 0.5, 0.5)
}),
..style.active(&theme::Radio::Default, is_selected)
}
}
fn hovered(&self, style: &Self::Style, is_selected: bool) -> radio::Appearance {
style.hovered(&theme::Radio::Default, is_selected)
}
}
➡️ Next: More Than One Page
📘 Back: Table of contents