arkui Swiper + Grid Demo

15 阅读1分钟

@Entry @Component struct SwiperGridDemo { @State itemsA: string[] = [] @State itemsB: string[] = []

// 可选:想监听/控制 Grid 滚动就传 Scroller private gridScrollerA: Scroller = new Scroller() private gridScrollerB: Scroller = new Scroller() aboutToAppear() { this.itemsA = [] for (let i = 0; i < 18; i++) this.itemsA.push('A' + (i + 1))

this.itemsB = [] for (let i = 0; i < 30; i++) this.itemsB.push('B' + (i + 1)) } @Builder pageTitle(title: string) { Text(title) .fontSize(18) .fontWeight(FontWeight.Medium) .padding({ left: 16, top: 12, bottom: 8 }) }

@Builder gridCell(text: string) { // 做一个简单“卡片” Column() { Text(text).fontSize(14) } .width('100%') .height(72) .borderRadius(12) .backgroundColor(0xF2F3F5) .justifyContent(FlexAlign.Center) }

@Builder gridPageA() { Column() { this.pageTitle('Page 1: Swiper + Grid(固定 3 列)')

  Grid(this.gridScrollerA) {
    ForEach(this.itemsA, (it: string) => {
      GridItem() {
        this.gridCell(it)
      }
    }, (it: string) => it)
  }
  .columnsTemplate('1fr 1fr 1fr')
  .columnsGap(12)
  .rowsGap(12)
  .padding(16)
  .height('100%')
}
.width('100%')
.height('100%')

}

@Builder gridPageB() { Column() { this.pageTitle('Page 2: Swiper + Grid(4 列 + 更紧凑)')

  Grid(this.gridScrollerB) {
    ForEach(this.itemsB, (it: string) => {
      GridItem() {
        // 更小的格子
        Column() { Text(it).fontSize(12) }
          .width('100%')
          .height(56)
          .borderRadius(10)
          .backgroundColor(0xE9EEF6)
          .justifyContent(FlexAlign.Center)
      }
    }, (it: string) => it)
  }
  .columnsTemplate('1fr 1fr 1fr 1fr')
  .columnsGap(10)
  .rowsGap(10)
  .padding(16)
  .height('100%')
}
.width('100%')
.height('100%')

}

build() { // Swiper 每个子组件就是一页 :contentReference[oaicite:3]{index=3} Column() { Swiper() { this.gridPageA() this.gridPageB() } .indicator(true) .loop(false) .width('100%') .height('100%') } .width('100%') .height('100%') } }