【鸿蒙 HarmonyOS】Swiper组件

一、背景

项目中通常会遇到图片轮播,内容轮播的场景;如:在一些应用首页显示推荐的内容时,需要用到轮播显示的能力。

二、源码地址

✍Gitee开源项目地址👉:https://gitee.com/cheinlu/harmony-os-next-swiper

文档地址👉:文档中心

三、实现效果

  

四、代码示例

@Entry
@Component
struct Index {
  //轮播图数据源
  @State swiperList: ResourceStr[] = [
    $r("app.media.swiper_one"), $r("app.media.swiper_two"), $r("app.media.swiper_three"), $r("app.media.swiper_four"),
    $r("app.media.swiper_five")
  ]
  @State selectedIndex: number = 0 //默认选中索引为0

  build() {
    Stack({ alignContent: Alignment.Bottom }) {
      Swiper() {
        ForEach(this.swiperList, (item: ResourceStr, index: number) => {
          Image(item)
            .width('100%')
            .height('100%')
        })
      }
      .onChange((index: number) => {
        this.selectedIndex = index
      })
      .autoPlay(true)
      .indicator(false)
      .itemSpace(0)
      .width('100%')
      .height('100%')

      //此处为自定义角标
      if (this.swiperList.length > 1) {
        List({ space: 5 }) {
          ForEach(this.swiperList, (item: ResourceStr, index: number) => {
            ListItem() {
              Image(this.selectedIndex === index ? $r("app.media.carousel_blue") : $r("app.media.carousel_gary"))
                .width(20)
                .aspectRatio(1)
            }
          })
        }
        .listDirection(Axis.Horizontal)
        .align(Alignment.Center)
        .enableScrollInteraction(false)
        .hitTestBehavior(HitTestMode.Transparent)
        .constraintSize({ maxWidth: '90%' })
        .height(20)
        .margin({ left: 20, bottom: 20, right: 20 })
      }
    }
  }
}

4.1、属性说明

autoPlay:子组件是否自动播放。默认值:false

indicator:是否启用导航点指示器。默认值:true

itemSpace:设置子组件与子组件之间间隙。默认值:0。说明:不支持设置百分比。

4.2、自定义角标

官方文档默认角标效果:

通过如下代码更改角标样式,更换成菱形图片选中与未选中替换样式

🚀🚀🚀  踩坑不易,还希望各位大佬支持一下

📃 我的土拨鼠开源项目:

✍Gitee开源项目地址👉:https://gitee.com/cheinlu/groundhog-charging-system

✍GitHub开源项目地址👉:https://github.com/cheinlu/groundhog-charging-system

📃 我的鸿蒙NEXT轮播图开源组件:https://gitee.com/cheinlu/harmony-os-next-swiper

最后:👏👏😊😊😊👍👍  

  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值