前言:我们的App列表中有展开的标签列表,标签的内容还不是固定的,内容有长有短,样式都是一样的,我尝试过GirdRow,Grid等组件,但是效果都不太好,因为栅栏组件实现那种固定宽高的比较合适,或者固定列的,这种比较个性化的标签不太好实现,需要用些比较特殊的方法,因为涉及到隐藏和显示,我开始的布局不会自动算高,写完就展示整个屏幕了,没有好的方法,后来根据Api可以设置自动算高的属性,就解决了这个问题。如果你有更好的例子,可以让我参考学习一下。
布局方式:
采用的是:Stack + Flex的布局,因为我们的列表是屏幕的一半,我这里举例也是采用屏幕宽度的’60%',宽度固定,高度不固定,需要将组件的高度属性,设置为auto,将容器的高度也设置为auto,这样整个组件就自动算高了,就可以达到我们的需求了,可以隐藏和显示了,也不需要设置固定的高度了。
完整代码如下:
@Extend(Text) function fancyText(weightValue: number, color: ResourceColor,size: number | string | Resource) {
.fontStyle(FontStyle.Normal)
.fontWeight(weightValue)
.fontSize(size)
.fontColor(color)
}
@Entry
@Component
struct StackSample {
private arr: string[] = ['APP1', 'APP2', 'APP3', '完美采集优秀门店标准店', 'APP7', '完美采集优秀门店标准店'];
//模仿数据
private itemTitleList: string[] = ['门店标签1', '门店标签2', '门店标签3', '门店标签4'];
build() {
Column() {
ForEach(this.itemTitleList, (item: string, index: number) => {
ExpandTagView({ itemList: this.arr, title: item })
}, (item: string) => JSON.stringify(item))
}
.width('60%')
.height('auto')
.backgroundColor('#efef')
}
}
@Component
struct ExpandTagView{
private itemList?: string[] = [];
private title?: string = ''
build() {
Stack({ alignContent: Alignment.TopStart }) {
Flex({ wrap: FlexWrap.Wrap }){
Text(this.title + ':')
.fancyText(300,'#353535',13)
.padding(2)
.borderRadius(2)
}
.width('33.33%')
.backgroundColor(Color.Orange)
Flex({ wrap: FlexWrap.Wrap }) {
ForEach(this.itemList, (item:string,index: number) => {
Text(item)
.fancyText(300,'#66b451',13)
.margin(1)
.textAlign(TextAlign.Center)
.borderRadius(2)
.backgroundColor('#efefef')
.padding(2)
}, (item: number) => JSON.stringify(item))
}
.width('66.66%')
.height('auto')
.margin({left:'33.33%'})
}
.width('100%')
.height('auto')
.padding(2)
}
}
效果图如下:
这样的标签列表就完美实现了,可以动态的计算高度,也可以在列表中展示和隐藏了,完美实现了需求。