一、目标
实现如下效果,选中tab
进行高亮:
使用系统提供TAB
组件,默认展示如下,与需求不符:
二、开撸
2.1 分析
标题无法满足需求,但还想使用tabs
的滑动功能,嗯,那就利用Stack
布局自定义头部,实现覆盖,并与Tab
关联就好啦。
2.2 code
import { TabClass } from '@hp/basic'
@Preview
@Component
export struct Task {
tabController: TabsController = new TabsController()
@State tabsData: TabClass[] = [{
name: 'waiting',
title: '待提现'
}, {
name: 'line',
title: '在途'
}, {
name: 'finish',
title: '已完成'
}]
@State currentIndex: number = 0
isCurrentSelect(item: TabClass) {
return this.tabsData[this.currentIndex].name === item.name
}
@Builder
getTabBar(item: TabClass) {
Column() {
Text(item.title)
.fontSize(16)
.fontColor(this.isCurrentSelect(item) ? $r('app.color.text_primary') : $r('app.color.text_secondary'))
.fontWeight(600)
.animation({
duration: 100
})
.margin({ bottom: 10 })
Divider()
.strokeWidth(4)
.width(this.isCurrentSelect(item) ? 24 : 0)
.color($r('app.color.primary'))
.lineCap(LineCapStyle.Round)
.animation({
duration: 100
})
}
.onClick(() => {
this.tabController.changeIndex(this.tabsData.findIndex((i) => item.name === i.name))
})
}
build() {
Stack({ alignContent: Alignment.Top }) {
Tabs({ barPosition: BarPosition.Start, index: $$this.currentIndex, controller: this.tabController }) {
ForEach(this.tabsData, (item: TabClass) => {
TabContent() {
Text(item.title)
}.tabBar(item.title)
})
}
.width('100%')
.animationDuration(300)
.backgroundColor($r('app.color.background_page'))
// 自定义TAB
Row({ space: 30 }) {
ForEach(this.tabsData, (item: TabClass) => {
this.getTabBar(item)
})
}
.width('100%')
.padding({ left: 30, right: 30 })
.backgroundColor(Color.White)
.height(50)
}
}
}
三、小结
- 遇事不要慌
- 灵活变通