按钮与开关
beginner
前言
WARNING
本教程面向已掌握JSON-UI基础知识的用户,建议先阅读JSON UI技术文档再继续学习。
在JSON-UI中创建自定义按钮和开关是常见需求。本指南将解析其运作机制,并提供详细的创建步骤说明。
为简化示例,我们将直接引用原版游戏中的按钮和开关组件。
开关控件
本示例基于ui/ui_template_toggles.json实现:
RP/ui/your_file.json
json
{
"our_toggle@common_toggles.light_text_toggle": {
"size": [64,32],
"$button_text": "点击我!",
"$toggle_name": "wiki_toggle", // 必填字段(仅在使用硬编码开关名称时生效)
"$toggle_view_binding_name": "wiki_toggle_state" // 用于数据绑定的开关标识符
}
}完成!现在你已成功创建可交互开关,可将其添加到任意界面进行测试。
开关还可用于控制其他UI元素的可见性:
RP/ui/your_file.json
json
{
"our_toggle@common_toggles.light_text_toggle": {
"size": [64,32],
"$button_text": "点击我!",
"$toggle_name": "wiki_toggle",
"$toggle_view_binding_name": "wiki_toggle_state"
},
"our_image": {
"type": "image",
"texture": "textures/items/apple",
"size": [16,16],
"offset": [0,20],
"bindings": [
{
"binding_type": "view",
"source_control_name": "wiki_toggle_state", // 需与$toggle_view_binding_name保持一致
"source_property_name": "#toggle_state", // 返回布尔值的开关状态
"target_property_name": "#visible"
}
]
}
}按钮控件
按钮功能相对有限,主要用于硬编码场景(如界面跳转或弹窗触发)。
本示例基于ui/ui_template_buttons.json实现:
RP/ui/your_file.json
json
{
"our_button@common_buttons.light_text_button": {
"size": [64,32],
"$button_text": "点击我!",
"$pressed_button_name": "button.menu_exit" // 必填字段,可使用全局按钮名称或硬编码按钮名称
}
}完成!现在点击按钮将退出当前界面,可添加到任意屏幕测试效果。
高阶应用
悬停提示
要实现悬停显示文本的按钮,需使用**内容按钮(Content Buttons)**组件。
本示例结合ui/ui_template_buttons.json和ui/ui_common.json实现:
RP/ui/your_file.json
json
{
"our_button@common_buttons.light_content_button": {
"size": [18,18],
"$button_content": "namespace.our_button_content_panel", // 指向内容元素
"$pressed_button_name": "button.menu_exit" // 必填字段
},
"our_button_content_panel": {
"type": "panel",
"controls": [
{
"our_image": {
"type": "image",
"texture": "textures/items/apple",
"size": [16,16]
}
},
{
// 可使用任意元素,这里采用游戏内物品悬停文本样式
"our_hover_text@common.hover_text": {
"ignored": "$default_state", // 必填字段:非悬停状态隐藏元素
"property_bag": {
"#hover_text": "" // 在此填入提示文本(不支持本地化,需自定义样式实现多语言)
}
}
}
]
}
}动画触发
要通过按钮触发动画,需在动画的play_event属性中指定$pressed_button_name。
示例:
RP/ui/your_file.json
json
{
"example_animation": {
"anim_type": "offset",
"easing": "linear",
"duration": 2,
"from": [0,0],
"to": [-50,0],
"play_event": "button.example_button_id"
},
"example_button@common_buttons.light_text_button": {
"$pressed_button_name": "button.example_button_id", // 动画play_event需与此ID对应
"$button_text": "播放动画",
"size": [80,20]
},
"example_label": {
"type": "label",
"text": "示例文本",
"anims": ["@namespace.example_animation"], // 在此关联动画
"anchor_from": "top_right",
"anchor_to": "top_right"
}
}