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 '_with' suffix related methods to MouseArea to support closures #2661

Open
wants to merge 3 commits into
base: master
Choose a base branch
from

Conversation

jellybobbin
Copy link

This PR adds a series of on_xxx_with methods to MouseArea to support closures, to better support features such as list selection.

Example 例子

截屏2024-11-04 23 43 50

Example code

use iced::widget::{center, column, container, mouse_area, text};
use iced::{Center, Fill};

struct App {
    data: Vec<i32>,
    selected: usize,
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum Message {
    Selected(usize),
}

impl Default for App {
    fn default() -> Self {
        App::new()
    }
}

impl App {
    pub fn new() -> Self {
        Self {
            data: vec![100, 200, 300],
            selected: 0,
        }
    }
    fn update(&mut self, message: Message) {
        match message {
            Message::Selected(i) => self.selected = i,
        }
    }
    fn view(&self) -> iced::Element<Message> {
        let mut columns = column![];
        for (i, v) in self.data.iter().enumerate() {
            let mut item = center(text(v.to_string()).align_x(Center)).width(Fill);
            if i == self.selected {
                item = item.style(container::rounded_box)
            }
            columns = columns.push(mouse_area(item).on_release_with(move || Message::Selected(i)));
        }

        columns.spacing(2).into()
    }
}

fn main() {
    iced::application("Mouse Area", App::update, App::view)
        .window_size((200.0, 100.0))
        .centered()
        .run()
        .unwrap();
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant