自由,分享
rust-iced框架-输入框和文本更新

图片-1698290466657

use iced::{widget::{ Column, Text, Row, Button, text, text_input}, Sandbox, Length, Settings, Font, font::{Family, Weight}};

fn main() -> iced::Result{
    Counter::run(Settings {
        default_font: Font { //设置字体
            family: Family::Name("思源黑体 CN"),
            weight: Weight::Normal,
            ..Default::default()
        },
        ..Default::default() 
    })
}

#[derive()]
struct Counter{
    value:i32,
    input_value:String,
    label:String,
    
}

#[derive(Debug,Clone)]
enum Message {//枚举
    IncrementPressed,
    DecrementPressed,
    Chageinput(String),
    Chagelabel,
}

impl Sandbox for Counter {
    type Message =Message;

    fn new() -> Self {
        Self { 
            value: 0,
            input_value:"你好".to_string(),
            label:"".to_string(),}
    }

    fn title(&self) -> String {//设置窗口标题
        String::from("pcb")
    }

    fn update(&mut self, message: Self::Message) {
        //逻辑更新
        match message {
            Message::IncrementPressed => {
                self.value += 1;
            }
            Message::DecrementPressed => {
                self.value -= 1;
            }
            Message::Chageinput(input_value) => {
                self.input_value = input_value;
            }
            Message::Chagelabel => {
                self.label = self.input_value.clone();
            },
        }
    }

 
    fn view(&self) -> iced::Element<'_, Self::Message> {
        //定义小组件
        let anniujia =Button::new("+").on_press(Message::IncrementPressed).width(Length::Fill);
        let anniujian=Button::new("-").on_press(Message::DecrementPressed).width(Length::Fill);
        let input = text_input("What needs to be done?",&self.input_value)
        .on_input(Message::Chageinput);
        let send = Button::new("发送").on_press(Message::Chagelabel).width(Length::Fill);
        let label = text(&self.label).size(22);
        //组件布局
        Column::new().push(
            Text::new("pcb的计算器")
        ).push(
            Row::new().push(
                anniujia,
            ).push(
                text(self.value).size(22),
            ).push(anniujian,
        )).push(Row::new().push(
            input
            ).push(send
        )).push(Row::new().push(
            label))
        .align_items(iced::Alignment::Center).into()
    }
}