import { curves } from '@kit.ArkUI';
interface Data { //数据类型 src: ResourceStr txt: string}
@Entry@Componentstruct Waterflowpage { @State datas: Data[] = []//默认数据源 @State templete: string = '1fr'//默认列数
aboutToAppear(): void { //模拟生成数据源 for (let i = 1; i <= 100; i++) { this.datas.push({ src: i % 2 == 0 ? $r('app.media.img1') : $r('app.media.img2'), txt: 'N' + i }) } }
@Builder genitem(src: ResourceStr, txt: string) { //瀑布流子布局 有图片和文本 图片高度不一样 Column() { Image(src).width('100%') Text(txt).fontSize(18).fontWeight(FontWeight.Bold).margin(10) }.width('100%') }
build() { Stack() { Column() { WaterFlow() { ForEach(this.datas, (item: Data) => { FlowItem() { this.genitem(item.src, item.txt) } }, (item: Data) => JSON.stringify(item)) }.columnsTemplate(this.templete) .rowsGap(20) .columnsGap(10) .animation({ curve: curves.springMotion() }) //切换列数的时候有动画 } .height('100%') .width('100%')
Button('变化').width('60%').backgroundColor('rgba(255,0,0,0.5)') .onClick(() => { let count = Math.floor(Math.random() * 5 + 1) //生成随机列数1~5 let str = '' for (let i = 1; i <= count; i++) { //生成列数字符串 str = str + '1fr ' } this.templete = str }) }.width('100%') .height('100%') .alignContent(Alignment.Bottom) }}
评论