鸿蒙NEXT中实现轮播图效果

162 阅读2分钟

轮播图核心组件Swiper

1.1 swiper

首先Swiper组件提供滑动轮播显示的能力。Swiper本身就是一个容器组件,当设置了多个子组件后,可以实现其轮播显示

实现数字轮播:

image.png

Swiper() {
// 轮播内容 
Text('0')
   .textAlign(TextAlign.Center)
   .backgroundColor(Color.Red)
   .fontColor(Color.White)
   .fontSize(30)
 Text('1')
   .textAlign(TextAlign.Center)
   .backgroundColor(Color.Green)
   .fontColor(Color.White)
   .fontSize(30)
 Text('2')
   .textAlign(TextAlign.Center)
   .backgroundColor(Color.Blue)
   .fontColor(Color.White)
   .fontSize(30)
// (设置尺寸,撑开swiper)
}
// 设置尺寸(内容拉伸、优先级高)
.width('100%')
.height(100)

##1.2 常用属性

image.png

  Swiper() {
    Text('0')
      .textAlign(TextAlign.Center)
      .backgroundColor(Color.Red)
      .fontColor(Color.White)
      .fontSize(30)
    Text('1')
      .textAlign(TextAlign.Center)
      .backgroundColor(Color.Green)
      .fontColor(Color.White)
      .fontSize(30)
    Text('2')
      .textAlign(TextAlign.Center)
      .backgroundColor(Color.Blue)
      .fontColor(Color.White)
      .fontSize(30)
  }
  .loop(true)`//是否开启循环`
  .width('100%')
  .height(160)
  .autoPlay(true)`//控制子组件是否自动播放`
  .interval(1000)`//使用自动播放时,每个图片轮换的时间间隔,单位是毫秒默认是3000(3秒)`
  .vertical(true)`//设置是否为纵向滑动/默认是false;如图当设置为true时实现纵向滑动,同时导航点改为纵向排布`

2.1 调整导航点

1.显示/隐藏

2.设置导航点类型: a.圆点类型 b.数字类型

圆点类型:

image.png

数字类型:

image.png

Swiper(){
// 略
}
// .indicator(false) // 关闭导航
// .indicator(Indicator.dot()) // 圆点指示器(默认)
// .indicator(Indicator.digit()) // 数字指示器

3.设置导航点位置\

image.png 鸿蒙中如何调整其位置像:
left、top、right、bottom -- 可以调整其与swipper的距离;
设置导航点样式:
itemWidth\itemHeight -- 可以设置其通常情况下的宽度和高度;
selectedItemWidth\selectedItemHeight -- 可以设置其在选中状态下的宽度和高度
设置导航点的颜色:
color -- 设置通常情况下的颜色
selectedColor --设置选中时的颜色

Swiper() {
     // 略
  }
  .width('100%')
  .height(160)
  .indicator(
    Indicator.dot() // 圆点
      .selectedColor(Color.White) // 选中颜色
      .selectedItemWidth(30) // 选中宽度
      .selectedItemHeight(4) // 选中高度
      .itemWidth(10) // 默认宽度
      .itemHeight(4) // 默认宽度
  )

3.1 swiper轮播图页面切换

image.png
实现轮播图的手动切换有3个核心步骤:
1.实例化控制器
2.设置给Swiper
3.调用控制器方法
SwiperController对象核心方法
showNext():void ---下一页
showPrevious():void ---上一页\

@Entry
@Component
struct SwiperDemo {
  // 1.创建控制器对象
  controller: SwiperController = new SwiperController()

  build() {
    Column({ space: 10 }) {
      // 2. 设置给 Swiper
      Swiper(this.controller) {
        // 略
      }
      Row() {
        Button('上一页')
          .onClick(() => {
            // 3.调用控制器的方式实现切换效果
            this.controller.showPrevious()
          })
        Button('下一页')
          .onClick(() => {
            this.controller.showNext()
          })
      }

    }
    .width('100%')
    .height('100%')

    // .padding(20)
  }
}