Switch 开关
表示立即生效的开/关状态,例如启用通知。状态由 bool 变量持有。
在线体验
点击开关,或聚焦画布后按空格,查看画布下方的状态反馈。 工具栏支持 Ant Design、Element Plus、shadcn 以及深浅色切换;重置会恢复初始状态。
Switch 开关 · 在线体验真实 Go 组件
在独立页面打开 ↗基本用法
下面代码放在应用的页面文件中;完整的 main 和窗口初始化见 打开自绘窗口。
go
import (
"github.com/tangoui/tango/ui"
)
var enabled bool
func page(c *ui.Context) {
if ui.Switch(c, &enabled).Changed() {
// enabled 已经更新,可在这里处理业务逻辑。
}
}常用参数与方法
| 参数 / 方法 | 说明 |
|---|---|
val *bool | 应用持有的开关值 |
Texts(on, off string) | 设置开关内的状态文字 |
Small() | 紧凑尺寸 |
Loading(bool) | 加载状态 |
Disabled(bool) | 禁用开关 |
Changed() bool | 当前帧是否发生状态切换 |
使用说明
开关适合修改设置;需要用户确认提交的多项选中状态,通常使用 Checkbox。
更多场景
官方 gallery 里这个组件的全部示例(基础、进阶与组合场景),可切换场景、主题和深浅色。
Switch 开关 / Slider 滑动输入条 · 在线体验真实 Go 组件
在独立页面打开 ↗实现与更多示例
全部示例代码
以下是上方在线演示运行的 Go 源码(来自官方 gallery),点击标题展开。函数接收的 c *ui.Context 由窗口的 UI 循环每帧传入,接入方式见 Go GUI 入门。
完整 API
签名与说明由 site/tools/compdoc 从 Go 源码和文档注释提取;点击名称跳到 Go API 参考 的对应条目。
入口函数
ui.Switch
go
func Switch(c *Context, val *bool) *SwitchWSwitch adds a switch bound to *val.
返回 *SwitchW,可链式调用的方法见 SwitchW 方法。
SwitchW 方法
ui.SwitchW:SwitchW is a toggle switch.
| 方法 | 说明 | 签名 |
|---|---|---|
A11yLabel | A11yLabel sets the accessible name (a switch has no visible label; inside a FormItem the item label is used). | A11yLabel(s string) *SwitchW |
ActionIcons | ActionIcons shows an icon on the thumb (Element active-action-icon / inactive-action-icon), in the track color of the state. | ActionIcons(on, off *icon.Icon) *SwitchW |
BeforeChange | BeforeChange is asked before every toggle with the value the switch would take; returning false keeps the current value. | BeforeChange(fn func(next bool) bool) *SwitchW |
BeforeChangeAsync | BeforeChangeAsync asks fn before every toggle; the switch shows loading and ignores clicks until fn calls done (from any goroutine, once): with true the switch takes next, with false it stays. | BeforeChangeAsync(fn func(next bool, done func(ok bool))) *SwitchW |
Changed | Changed() bool | |
Disabled | Disabled(on bool) *SwitchW | |
Icons | Icons shows on / off icons inside the track (Element inline-prompt with active-icon / inactive-icon). | Icons(on, off *icon.Icon) *SwitchW |
Large | Large selects the large switch. | Large() *SwitchW |
Loading | Loading(on bool) *SwitchW | |
OuterTexts | OuterTexts shows labels beside the track (Element active-text / inactive-text): off before it, on after it; the label of the current state takes the brand color. | OuterTexts(on, off string) *SwitchW |
Size | Size sets the switch size (Small, Middle or Large). | Size(s ControlSize) *SwitchW |
Small | Small() *SwitchW | |
Texts | Texts shows on / off text inside the track (Ant checkedChildren, Element inline-prompt). | Texts(on, off string) *SwitchW |
Width | Width sets the track width in px (Element width); by default the track has the theme's minimum width and grows to fit the inline texts. | Width(px float32) *SwitchW |