Badge徽章
查看源码components/badge.go自然宽度#
短标签按内容测量宽度,而不是平分容器。
labels := []string{"New", "99+", "Published"}
variants := []components.BadgeVariant{
components.BadgeDefault, components.BadgeSecondary, components.BadgeOutline,
}
x := bounds.X
for index, label := range labels {
width, height := components.BadgeExtent(canvas, theme, label)
badge := ui.Rect{X: x, Width: width, Height: height}
components.PaintBadge(canvas, theme, badge, label, variants[index])
x += width + 12
}六种变体#
默认、次要、危险、描边、幽灵与链接外观;均为展示标签。
labels := []string{"Default", "Secondary", "Destructive", "Outline", "Ghost", "Link"}
variants := []components.BadgeVariant{
components.BadgeDefault, components.BadgeSecondary, components.BadgeDestructive,
components.BadgeOutline, components.BadgeGhost, components.BadgeLink,
}
x := bounds.X
for index, label := range labels {
width, height := components.BadgeExtent(canvas, theme, label)
badge := ui.Rect{X: x, Width: width, Height: height}
components.PaintBadge(canvas, theme, badge, label, variants[index])
x += width + 12
}长中文#
完整展示长中文及中英混排标签,空间不足时另起一行。
// BadgeExtent keeps each badge as wide as its label, so a grid can wrap them.
labels := []string{"In review", "This is a long status label", "Viva native component · Published"}
variants := []components.BadgeVariant{
components.BadgeSecondary, components.BadgeOutline, components.BadgeDefault,
}
x := bounds.X
for index, label := range labels {
width, height := components.BadgeExtent(canvas, theme, label)
badge := ui.Rect{X: x, Width: width, Height: height}
components.PaintBadge(canvas, theme, badge, label, variants[index])
x += width + 12
}安装
将组件源码复制到自己的项目,直接修改。
go run ./cmd/viva add --out ./components/local badge默认按内容确定宽度#
PaintBadge 测量文本并返回实际边界。传入起点即可,无需让徽章撑满容器。
- Default 用于强调,Secondary 更弱,Outline 使用描边,Destructive 表示错误状态。
- 长文本示例包含中英文混排;各平台的系统字体度量可能不同。
语义#
徽章是标签,不是按钮;不接受焦点,也不创建点击目标。需要执行操作时请使用按钮。
键盘操作
Tab 在控件间移动;Ctrl/⌘ K 搜索组件。进入预览后,键盘事件由 Go 运行时处理。