
To create a simple button with text you should do something like this:
#![allow(unused)]
fn main() {
fn create_button(ui: &mut UserInterface) -> Handle<UiNode> {
ButtonBuilder::new(WidgetBuilder::new())
.with_text("Click me!")
.build(&mut ui.build_ctx())
}
}
How to create a button using custom dimensions (100x100) and custom text alignment (Vertical centered and Horizontal
right aligned):
#![allow(unused)]
fn main() {
fn create_button_custom(ui: &mut UserInterface) -> Handle<UiNode> {
ButtonBuilder::new(WidgetBuilder::new().with_width(100.0).with_height(100.0))
.with_content(
TextBuilder::new(WidgetBuilder::new())
.with_text("Click me!")
.with_horizontal_text_alignment(HorizontalAlignment::Right)
.with_vertical_text_alignment(VerticalAlignment::Center)
.build(&mut ui.build_ctx()),
)
.build(&mut ui.build_ctx())
}
}
More fancy-looking button with an image as a background could be created using this code snippet:
#![allow(unused)]
fn main() {
fn create_fancy_button(
ui: &mut UserInterface,
resource_manager: ResourceManager,
) -> Handle<UiNode> {
let ctx = &mut ui.build_ctx();
ButtonBuilder::new(WidgetBuilder::new())
.with_back(
ImageBuilder::new(WidgetBuilder::new())
.with_texture(resource_manager.request::<Texture>("path/to/your/texture"))
.build(ctx),
)
.with_text("Click me!")
.build(ctx)
}
}
When clicked, a button sends a ButtonMessage::Click
message, you can catch it in your code and do something
useful:
#![allow(unused)]
fn main() {
#[derive(Debug, Reflect, Visit)]
struct MyGame {
button: Handle<UiNode>,
}
impl Plugin for MyGame {
fn on_ui_message(&mut self, _context: &mut PluginContext, message: &UiMessage) {
if let Some(ButtonMessage::Click) = message.data() {
if message.destination() == self.button {
}
}
}
}
}
This example shows how to create a button that will close your game.
#![allow(unused)]
fn main() {
#[derive(Visit, Reflect, Debug)]
struct Game {
quit_button_handle: Handle<UiNode>,
}
fn create_quit_button(ui: &mut UserInterface) -> Handle<UiNode> {
ButtonBuilder::new(WidgetBuilder::new())
.with_content(
TextBuilder::new(WidgetBuilder::new())
.with_text("Quit")
.build(&mut ui.build_ctx()),
)
.build(&mut ui.build_ctx())
}
impl Game {
fn new(ctx: PluginContext) -> Self {
Self {
quit_button_handle: create_quit_button(ctx.user_interfaces.first_mut()),
}
}
}
impl Plugin for Game {
fn on_ui_message(&mut self, context: &mut PluginContext, message: &UiMessage) {
if let Some(ButtonMessage::Click) = message.data() {
if message.destination() == self.quit_button_handle {
if let Some(window_target) = context.window_target {
window_target.exit();
}
}
}
}
}
}