鸿蒙布局元素篇(六)-创建轮播(Swiper)

277 阅读2分钟

轮播图也是移动端常见的功能,官方也是将常见的一些功能做了封装处理。

参数

参数名参数描述
controller给组件绑定一个控制器,用来控制组件翻页。

独有属性

参数名参数描述
index设置当前在容器中显示的子组件的索引
autoPlay子组件是否自动播放。
interval使用自动播放时播放的时间间隔,单位为毫秒。
indicator是否启用导航点指示器。
loop是否开启循环。
vertical是否为纵向滑动。
itemSpace设置子组件与子组件之间间隙。
displayMode主轴方向上元素排列的模式,优先以displayCount设置的个数显示
cachedCount设置预加载子组件个数。
disableSwipe禁用组件滑动切换功能。
indicatorStyle设置导航点样式
displayCount设置一页内元素显示个数。
effectMode滑动效果

同List容器一样,也是提供了很多属性。也是实现通过实现功能的方式展示以上特性的用法。

包含以下功能

  • 横向轮播图
  • 支持自动播放,手指按在轮播图上时停止
  • 支持手指滑动切换
  • 含有导航点指示器
  • 支持外部按钮切换
  • 最后一页时,下一页为第一页,同理第一页的前一页为最后一页
// Text提点公共样式
@Extend(Text) function swiperItem () {
  .width(250)
  .height(250)
  .textAlign(TextAlign.Center)
  .fontSize(50)
  .fontColor('#fff')
  .fontWeight(FontWeight.Bold)
}
// Button提点公共样式
@Extend(Button) function changeButton () {
  .fontSize(20)
  .height(50)
  .backgroundColor('#65a076')
}

@Entry
@Component
struct SwiperDemo {
  // 给轮播容器添加滚动控制器,用来外部手动调节控制的
  private swiperController: SwiperController = new SwiperController();
  build() {
    Column({ space: 5 }) {
      Swiper(this.swiperController) {
        Text("0")
          .swiperItem()
          .backgroundColor('#4f7371')
        Text("1")
          .swiperItem()
          .backgroundColor('#73402c')
        Text("2")
          .swiperItem()
          .backgroundColor('#063c73')
      }
      // 自动播放
      .autoPlay(true)
      // 自动播放间隔
      .interval(2000)
      // 循环播放,就是最后一页的下一页为第一页,同理第一页的前一页为最后一页
      .loop(true)
      // 启动导航点指示器,就是左下角粉粉的那几个
      .indicator(true)
      // 指示器那几个点的样式,激活和不激活的状态
      .indicatorStyle({
        size: 30,
        color: '#b574a8',
        selectedColor: '#b5a3b5',
        left: 50
      })
      // 轮播的动画效果,Ease 先慢再块在慢,但是效果不明显-_-
      .curve(Curve.Ease)
      // 滑动到边缘的动画,Spring是有点惯性,但是效果不明显-_-
      .effectMode(EdgeEffect.Spring)

      Row({ space: 12 }) {
        Button('上一页')
          .changeButton()
          .onClick(() => {
            this.swiperController.showPrevious(); // 通过controller切换到前一页
          })
        Button('下一页')
          .changeButton()
          .onClick(() => {
            this.swiperController.showNext(); // 通过controller切换到后一页
          })
      }.margin(5)
    }.width('100%')
    .margin({ top: 5 })
  }
}

实现效果

轮播图.gif