鸿蒙自定义Tabs居左对齐最简实现
2024-07-26 本文已影响0人
尼古拉斯小韭菜
鸿蒙官方Tabs是不支持居左对齐的,有时候我们希望我们的Tab能居左对齐,像这样
image.png如果要自定义组件实现麻烦还容易出现各种BUG,网上也有自己现实的但是实在繁琐效果还不好,这里教大家一种我自己实践出来的简单方法,我们可以通过自定义Tab的最后一个标签的右边距来实现整个Tab控价的左移,但同时TabContent页面保持原位不动的效果,下边来看代码。
@Entry
@Component
struct TabsPage {
@State tabBarArray: string[] = ["SUV","燃油车","新能源","插电混动"]
@State currentIndex: number = 0;
@Builder
TabBuilder(index: number) {
Column() {
Text(this.tabBarArray[index])
.textAlign(TextAlign.Center)
.lineHeight(22)
.fontSize(this.currentIndex == index ? 16 : 16)
.fontWeight(this.currentIndex == index ? 600 : 400)
.fontColor((this.currentIndex == index ? "#3B86F6" : "#333333"))
Image(null)
.backgroundColor("#3B86F6")
.width(24)
.height(2)
.margin({ top: 6 })
.visibility(this.currentIndex == index ? Visibility.Visible : Visibility.Hidden)
}.alignItems(HorizontalAlign.Center).justifyContent(FlexAlign.Center)
.margin({
right: index == this.tabBarArray.length - 1 ? 80 : 0
})
.padding({ left: 12, right: 12})
}
build() {
Tabs() {
ForEach(this.tabBarArray, (tabsItem: string, index: number) => {
TabContent() {
Column() {
Text(tabsItem)
}.justifyContent(FlexAlign.Center).alignItems(HorizontalAlign.Center)
}.tabBar(this.TabBuilder(index)).backgroundColor("#f00")
})
}
.barHeight("7.2%")
.barMode(BarMode.Scrollable)
.barWidth("100%")
.onChange((index: number) => {
this.currentIndex = index
})
.vertical(false)
}
}
如果我们要实现Tabs右边添加菜单,我们只需要按上边的方法让Tabs空出一部分距离,在相对布局中加入菜单即可,看代码
image.png
@Entry
@Component
struct TabsPage {
@State tabBarArray: string[] = ["SUV","燃油车","新能源","插电混动"]
@State currentIndex: number = 0;
@Builder
TabBuilder(index: number) {
Column() {
Text(this.tabBarArray[index])
.textAlign(TextAlign.Center)
.lineHeight(22)
.fontSize(this.currentIndex == index ? 16 : 16)
.fontWeight(this.currentIndex == index ? 600 : 400)
.fontColor((this.currentIndex == index ? "#3B86F6" : "#333333"))
Image(null)
.backgroundColor("#3B86F6")
.width(24)
.height(2)
.margin({ top: 6 })
.visibility(this.currentIndex == index ? Visibility.Visible : Visibility.Hidden)
}.alignItems(HorizontalAlign.Center).justifyContent(FlexAlign.Center)
.margin({
right: index == this.tabBarArray.length - 1 ? 80 : 0
})
.padding({ left: 12, right: 12})
}
build() {
RelativeContainer(){
Tabs() {
ForEach(this.tabBarArray, (tabsItem: string, index: number) => {
TabContent() {
Column() {
Text(tabsItem)
}.justifyContent(FlexAlign.Center).alignItems(HorizontalAlign.Center)
}.tabBar(this.TabBuilder(index)).backgroundColor("#f00")
})
}
.barHeight("7.2%")
.barMode(BarMode.Scrollable)
.barWidth("100%")
.onChange((index: number) => {
this.currentIndex = index
})
.vertical(false)
Image($r("app.media.app_icon")).width(20).height(20).alignRules({
top: { anchor: "__container__", align: VerticalAlign.Top },
right: { anchor: "__container__", align: HorizontalAlign.End }
}).margin({right:16, top: 14})
}.width("100%").height("100%")
}
}