Switch开关
查看源码components/switch.go受控开关#
点击改变目标状态,生产组件使用运行器的帧时钟过渡。
notify := f.Switch(tree.ID(page, "notifications"), enabled).Label("Desktop notifications")
if notify.Clicked() {
enabled = !enabled
}两种尺寸#
默认与紧凑开关独立受控。
f.Row().Gap(12).Children(func() {
if f.Switch(tree.ID(page, "default"), normal).Label("Default size").Clicked() {
normal = !normal
}
if f.Switch(tree.ID(page, "small"), compact).Label("Compact size").Small().Clicked() {
compact = !compact
}
})启用与禁用#
一个可切换开关和开、关两种禁用状态。
if f.Switch(tree.ID(page, "notify"), notify).Label("Desktop notifications").Clicked() {
notify = !notify
}
f.Switch(tree.ID(page, "off"), false).Label("Disabled · Off").Disabled(true)
f.Switch(tree.ID(page, "on"), true).Label("Disabled · On").Disabled(true)安装
将组件源码复制到自己的项目,直接修改。
go run ./cmd/viva add --out ./components/local switch明确的开关状态#
BeginSwitch 读取应用持有的布尔值。Label 命名控件,Small 改变紧凑尺寸,不创建不同的状态模型。
- 开关适合立即生效的设置,不应用来确认操作。
- 禁用开关仍然可见,但不会改变状态。
- 浏览器展示最终状态;原生过渡时序应在原生示例中验证。
键盘与状态#
Tab 聚焦可用开关,Enter 或空格通过点击处理器切换状态。颜色由静态类型的主题 token 决定。
键盘操作
Tab 在控件间移动;Ctrl/⌘ K 搜索组件。进入预览后,键盘事件由 Go 运行时处理。