Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Button::dynamic constructor #963

Merged
merged 3 commits into from
May 21, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions druid/src/widget/button.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,31 @@ impl<T: Data> Button<T> {
}
}

/// Construct a new dynamic button.
///
/// The contents of this button are generated from the data using a closure.
///
/// This is provided as a convenience; a closure can also be passed to [`new`],
/// but due to limitations of the implementation of that method, the types in
/// the closure need to be annotated, which is not true for this method.
///
/// # Examples
///
/// The following are equivalent.
///
/// ```
/// use druid::Env;
/// use druid::widget::Button;
/// let button1: Button<u32> = Button::new(|data: &u32, _: &Env| format!("total is {}", data));
/// let button2: Button<u32> = Button::dynamic(|data, _| format!("total is {}", data));
/// ```
///
/// [`new`]: #method.new
pub fn dynamic(text: impl Fn(&T, &Env) -> String + 'static) -> Self {
let text: LabelText<T> = text.into();
Button::new(text)
}

/// Provide a closure to be called when this button is clicked.
pub fn on_click(
self,
Expand Down
4 changes: 2 additions & 2 deletions druid/src/widget/label.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,8 @@ impl<T: Data> Label<T> {
/// ```
/// use druid::Env;
/// use druid::widget::Label;
/// let button1: Label<u32> = Label::new(|data: &u32, _: &Env| format!("total is {}", data));
/// let button2: Label<u32> = Label::dynamic(|data, _| format!("total is {}", data));
/// let label1: Label<u32> = Label::new(|data: &u32, _: &Env| format!("total is {}", data));
/// let label2: Label<u32> = Label::dynamic(|data, _| format!("total is {}", data));
totsteps marked this conversation as resolved.
Show resolved Hide resolved
/// ```
///
/// [`new`]: #method.new
Expand Down