跳转至

Button Prettify

在本节中,我们把按钮的文本替换为图标,并且添加文本悬浮提示。

首先需要创建包含图标的字体,可以在Fontello上选择图标,然后下载字体文件。将ttf版本的字体存放在项目下的fonts/editor-icon.ttf中。

然后在代码中加载字体文件,在iced::Settings中添加字体:

fn main() -> iced::Result {
    Editor::run(Settings {
        fonts: vec![include_bytes!("../fonts/editor-icon.ttf").as_slice().into()],
        ..Default::default() // Expand the default settings
    })
}

加载字体后,可以将按钮的输入文本替换为图标,使用text控件创建图标。在网页中可以读取到对应新建、打开、保存的Unicode编码分别为\u{E800}\u{F115}\u{E801}

fn toolbar_button<'a>(description: &str, callback: Message) -> Element<'a, Message> {
    let font = Font::with_name("editor-icon");

    let icon = text(match description {
        "new" => '\u{E800}',
        "open" => '\u{F115}',
        "save" => '\u{E801}',
        _ => ' '
    }).font(font);

    button(container(icon)
        .width(30)  // Set the width of the button
        .center_x() // Center the icon
    ).on_press(callback).into()
}

使用button_icon函数替换按钮原本的输入

// ... In `view` function
let controls = row![
    toolbar_button("new", Message::NewButtonPressed),
    toolbar_button("open", Message::OpenButtonPressed),
    toolbar_button("save", Message::SaveButtonPressed)
].spacing(10);

最后,实现悬浮提示,使用Tooltip控件包裹按钮即可。为了美观,可以通过style方法设置提示框的样式。

// ... In `view` function
let controls = row![
    toolbar_button("New", Message::NewButtonPressed),
    toolbar_button("Open", Message::OpenButtonPressed),
    toolbar_button("Save", Message::SaveButtonPressed)
].spacing(10);

// ... In the outer scope
fn toolbar_button<'a>(description: &str, callback: Message) -> Element<'a, Message> {
    let font = Font::with_name("editor-icon");
    let lower = description.to_lowercase();
    let icon = text(match lower.as_str() {
        "new" => '\u{E800}',
        "open" => '\u{F115}',
        "save" => '\u{E801}',
        _ => ' '
    }).font(font);

    tooltip(
        button(container(icon)
            .width(30)  // Set the width of the button
            .center_x() // Center the icon
        ).on_press(callback),
        description, tooltip::Position::FollowCursor
    ).style(theme::Container::Box).into() // Set the style of the tooltip
}

以下为完整的main.rs文件内容:

Download source code

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
use std::io;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use iced::{executor, theme, Application, Command, Element, Font, Length, Settings, Theme};
use iced::widget::{button, column, container, horizontal_space, row, text, text_editor, tooltip};

fn main() -> iced::Result {
    Editor::run(Settings {
        fonts: vec![include_bytes!("../fonts/editor-icon.ttf").as_slice().into()],
        ..Default::default()
    })
}

struct Editor {
    path: Option<PathBuf>,
    content: text_editor::Content,
    modified: bool,
    error: Option<Error>
}

#[derive(Debug, Clone)]
enum Message {
    EditorEdit(text_editor::Action),
    FileOpened(Result<(PathBuf, Arc<String>), Error>),
    FileSaved(Result<PathBuf, Error>),
    NewButtonPressed,
    OpenButtonPressed,
    SaveButtonPressed
}

impl Application for Editor {
    type Message = Message; // Define the type of messages
    type Theme = Theme;
    type Executor = executor::Default; // Engine for running async tasks
    type Flags = ();

    fn new(_flags: Self::Flags) -> (Self, Command<Message>) {
        (
            Self {
                content: text_editor::Content::new(),
                error: None,
                modified: false,
                path: None
            },
            Command::perform(
            load_file(format!("{}/src/main.rs", env!("CARGO_MANIFEST_DIR"))),
            Message::FileOpened
            )
        )
    }

    fn title(&self) -> String {
        String::from("A text editor")
    }

    fn update(&mut self, message: Message) -> Command<Message> {
        // Handle messages here
        match message {
            Message::EditorEdit(action) => {
                match &action {
                    text_editor::Action::Edit(_) => self.modified = true,
                    _ => {}
                }
                self.content.edit(action);
                Command::none()
            },
            Message::FileOpened(Ok((path, result))) => {
                self.path = Some(path);
                self.modified = false;
                self.content = text_editor::Content::with(&result);
                Command::none()
            },
            Message::FileSaved(Ok(path)) => {
                self.path = Some(path);
                self.modified = false;
                Command::none()
            },
            Message::FileOpened(Err(error)) | Message::FileSaved(Err(error)) => {
                self.error = Some(error);
                Command::none()
            },
            Message::NewButtonPressed => {
                self.content = text_editor::Content::new();
                self.error = None;
                self.path = None;
                self.modified = false;
                Command::none()
            },
            Message::OpenButtonPressed => {
                self.modified = false;
                Command::perform(pick_file(), Message::FileOpened)
            },
            Message::SaveButtonPressed => {
                let content = self.content.text();
                match self.modified {
                    false => Command::none(),
                    true => Command::perform(
                        save_file(self.path.clone(), content),
                        Message::FileSaved
                    )
                }
            }
        }
    }

    fn view(&self) -> Element<'_, Message> {
        // Create the user interface here
        let editor = text_editor(&self.content).on_edit(Message::EditorEdit);
        let controls = row![
            toolbar_button("New", Message::NewButtonPressed),
            toolbar_button("Open", Message::OpenButtonPressed),
            toolbar_button("Save", Message::SaveButtonPressed)
        ].spacing(10);

        // Query cursor position
        let path_indicator = if let Some(error) = &self.error {
            match error {
                Error::DialogClosed => text("Dialog closed"),
                Error::IO(kind) => text(format!("I/O error: {:?}", kind))
            }
        } else {
            let path_text = match &self.path {
                None => String::from("New file"),
                Some(path) => path.to_string_lossy().to_string()
            };
            let suffix = if self.modified { "*" } else { "" };
            text(format!("{}{}", path_text, suffix))
        };
        let cursor_indicator = {
            let (line, column) = self.content.cursor_position();

            text(format!("Line: {}, Column: {}", line + 1, column + 1))
        };
        let status_bar = row![
            path_indicator,
            horizontal_space(Length::Fill),
            cursor_indicator
        ];

        container(column![controls, editor, status_bar].spacing(10)).padding(10).into()
    }

    fn theme(&self) -> Theme {
        Theme::Dark
    }
}

async fn pick_file() -> Result<(PathBuf, Arc<String>), Error> {
    let file_handle = rfd::AsyncFileDialog::new()
        .set_title("Choose a text file...")
        .pick_file()
        .await
        .ok_or(Error::DialogClosed)?;
    load_file(file_handle.path()).await
}

async fn load_file(path: impl AsRef<Path>) -> Result<(PathBuf, Arc<String>), Error> {
    let content = tokio::fs::read_to_string(path.as_ref())
        .await
        .map(Arc::new)
        .map_err(|err| err.kind())
        .map_err(Error::IO);
    content.and_then(|content| Ok((path.as_ref().to_path_buf(), content)))
}

async fn save_file(path: Option<PathBuf>, content: String) -> Result<PathBuf, Error> {
    let path = if let Some(path) = path {
        path
    } else {
        rfd::AsyncFileDialog::new()
            .set_title("Save the file to...")
            .save_file()
            .await
            .ok_or(Error::DialogClosed)?
            .path()
            .to_path_buf()
    };
    tokio::fs::write(&path, content)
        .await
        .map_err(|err| err.kind())
        .map_err(Error::IO)
        .map(|_| path)
}

fn toolbar_button<'a>(description: &str, callback: Message) -> Element<'a, Message> {
    let font = Font::with_name("editor-icon");
    let lower = description.to_lowercase();
    let icon = text(match lower.as_str() {
        "new" => '\u{E800}',
        "open" => '\u{F115}',
        "save" => '\u{E801}',
        _ => ' '
    }).font(font);

    tooltip(
        button(container(icon)
            .width(30)  // Set the width of the button
            .center_x() // Center the icon
        ).on_press(callback),
        description, tooltip::Position::FollowCursor
    ).style(theme::Container::Box).into()
}

#[derive(Debug, Clone)]
enum Error {
    DialogClosed,
    IO(io::ErrorKind)
}

评论