Tabs:通过页签进行内容视图切换的容器组件,每个页签对应一个内容视图。仅支持子组件TabContent,以及渲染控制类型if/else和ForEach,不建议自定义组件作为子组件。TabContent设置页签的接口有以下三个:
TabBar的下划线不仅是视觉焦点,更是用户感知当前页面的关键信号,下面将提供TabBar下划线的三种制作方案,开发者可以按需参考使用:
方案 | 使用场景 |
|---|---|
基于tabBar(SubTabBarStyle)接口实现下划线效果。 | 基于SubTabBarStyle实现下划线,实现简单,但是对于复杂的页签栏样式无法满足。 |
基于tabBar(CustomBuilder)接口实现下划线效果。 | 下划线需要自定义实现,实现难度中等,页签栏样式开放程度高于方案一。 |
使用其他组件如List等,组合实现TabBar页签。 | 页签栏和下划线均自定义实现,页签栏样式丰富程度高,但实现较复杂。 |
方案一:基于tabBar(SubTabBarStyle)接口实现。
方案二:基于tabBar(CustomBuilder)接口实现。有以下两种实现方式:
@Entry
@Component
struct TabBarUnderLine {
fontColor: string = '#182431';
selectedFontColor: string = '#007DFF';
@State currentIndex: number = 0;
@State selectedIndex: number = 0;
private controller: TabsController = new TabsController();
@State dividerWidthArr: Length[] = [];
@Builder
tabBuilder(index: number, name: string) {
Column() {
Text(name)
.fontColor(this.selectedIndex === index ? this.selectedFontColor : this.fontColor)
.fontSize(16)
.fontWeight(this.selectedIndex === index ? 500 : 400)
.lineHeight(22)
.margin({ top: 17, bottom: 7 })
.onAreaChange((oldValue: Area, newValue: Area) => {
console.info(`${JSON.stringify(oldValue.width)} ${JSON.stringify(newValue.width)}`);
this.dividerWidthArr[index] = newValue.width;
});
Divider()
.strokeWidth(2)
.color('#007DFF')
.opacity(this.selectedIndex === index ? 1 : 0)
.width(this.dividerWidthArr[index]);
}.width('100%');
}
build() {
Column() {
Tabs({ barPosition: BarPosition.Start, index: this.currentIndex, controller: this.controller }) {
TabContent() {
Column().width('100%').height('100%').backgroundColor('#00CB87');
}.tabBar(this.tabBuilder(0, 'green'));
TabContent() {
Column().width('100%').height('100%').backgroundColor('#007DFF');
}.tabBar(this.tabBuilder(1, 'blue'));
TabContent() {
Column().width('100%').height('100%').backgroundColor('#FFBF00');
}.tabBar(this.tabBuilder(2, 'yellow'));
TabContent() {
Column().width('100%').height('100%').backgroundColor('#E67C92');
}.tabBar(this.tabBuilder(3, 'pink'));
}
.vertical(false)
.barMode(BarMode.Fixed)
.barWidth(360)
.barHeight(56)
.animationDuration(400)
.onChange((index: number) => {
// currentIndex控制TabContent显示页签
this.currentIndex = index;
this.selectedIndex = index;
})
.onAnimationStart((index: number, targetIndex: number, event: TabsAnimationEvent) => {
console.info(`${event}`);
if (index === targetIndex) {
return;
}
// selectedIndex控制自定义TabBar内Image和Text颜色切换
this.selectedIndex = targetIndex;
})
.width(360)
.height(296)
.margin({ top: 52 })
.backgroundColor('#F1F3F5');
}.width('100%');
}
} Q:TabBar怎么取消文字下划线?
A:使用tabBar(value: SubTabBarStyle | BottomTabBarStyle)接口,入参为BottomTabBarStyle,底部样式没有下划线效果。或者使用tabBar(options: string | Resource | CustomBuilder | TabBarOptions)接口,入参为CustomBuilder,不绘制下划线,则可取消文字下划线效果。