Skip to content

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 源码 ↗

实现与更多示例 ​

全部示例代码 ​

以下是上方在线演示运行的 Go 源码(来自官方 gallery),点击标题展开。函数接收的 c *ui.Context 由窗口的 UI 循环每帧传入,接入方式见 Go GUI 入门。

Switch 开关 / Slider 滑动输入条

gallery 演示 Switch 的 Render 函数,源码 page_form.go#L143。

加载中…

Switch 滑块图标 / Slider 反向与不包含

gallery 演示 SwitchAlign 的 Render 函数,源码 page_b1b.go#L82。

加载中…

完整 API ​

签名与说明由 site/tools/compdoc 从 Go 源码和文档注释提取;点击名称跳到 Go API 参考 的对应条目。

入口函数 ​

ui.Switch ​

go
func Switch(c *Context, val *bool) *SwitchW

Switch adds a switch bound to *val.

返回 *SwitchW,可链式调用的方法见 SwitchW 方法。

SwitchW 方法 ​

ui.SwitchW:SwitchW is a toggle switch.

方法说明签名
A11yLabelA11yLabel sets the accessible name (a switch has no visible label; inside a FormItem the item label is used).A11yLabel(s string) *SwitchW
ActionIconsActionIcons 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
BeforeChangeBeforeChange 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
BeforeChangeAsyncBeforeChangeAsync 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
ChangedChanged() bool
DisabledDisabled(on bool) *SwitchW
IconsIcons shows on / off icons inside the track (Element inline-prompt with active-icon / inactive-icon).Icons(on, off *icon.Icon) *SwitchW
LargeLarge selects the large switch.Large() *SwitchW
LoadingLoading(on bool) *SwitchW
OuterTextsOuterTexts 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
SizeSize sets the switch size (Small, Middle or Large).Size(s ControlSize) *SwitchW
SmallSmall() *SwitchW
TextsTexts shows on / off text inside the track (Ant checkedChildren, Element inline-prompt).Texts(on, off string) *SwitchW
WidthWidth 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

以 MIT 许可发布