Swiper组件提供滑动轮播显示的能力。Swiper本身是一个容器组件,当设置了多个子组件后,可以对这些子组件进行轮播显示。通常,在一些应用首页显示推荐的内容时,需要用到轮播显示的能力。
布局与约束
Swiper作为一个容器组件,如果设置了自身尺寸属性,则在轮播显示过程中均以该尺寸生效。如果自身尺寸属性未被设置,则分两种情况:如果设置了prevMargin或者nextMargin属性,则Swiper自身尺寸会跟随其父组件;如果未设置prevMargin或者nextMargin属性,则会自动根据子组件的大小设置自身的尺寸。
循环播放
通过loop属性控制是否循环播放,该属性默认值为true。
当loop为true时,在显示第一页或最后一页时,可以继续往前切换到前一页或者往后切换到后一页。如果loop为false,则在第一页或最后一页时,无法继续向前或者向后切换页面。
自动轮播
Swiper通过设置autoPlay属性,控制是否自动轮播子组件。该属性默认值为false。autoPlay为true时,会自动切换播放子组件,子组件与子组件之间的播放间隔通过interval属性设置。interval属性默认值为3000,单位毫秒。
导航点样式
Swiper提供了默认的导航点样式和导航点箭头样式,导航点默认显示在Swiper下方居中位置,开发者也可以通过indicator属性自定义导航点的位置和样式,导航点箭头默认不显示。通过indicator属性,开发者可以设置导航点相对于Swiper组件上下左右四个方位的位置,同时也可以设置每个导航点的尺寸、颜色、蒙层和被选中导航点的颜色。
练习Demo:SwiperPage
@Entry
@Component
struct SwiperPage {list: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9]build() {Column({ space: 10 }) {Text('Swiper轮播图练习')Swiper() {ForEach(this.list, (item: number) => {Column() {Text(item.toString()).width('90%').height(160).textAlign(TextAlign.Center).fontSize(30)}.width('100%').height('100%').backgroundColor((item + 2) % 2 == 0 ? 0xAFEEEE : '#ffdaffcf')})}.width('100%').aspectRatio(2).cachedCount(2).index(0).autoPlay(true).interval(4000).loop(true).indicatorInteractive(true).itemSpace(0).indicator( // 设置圆点导航点样式new DotIndicator().itemWidth(15).itemHeight(15).selectedItemWidth(15).selectedItemHeight(15).color(Color.Gray).selectedColor(Color.Blue)).displayArrow({// 设置导航点箭头样式showBackground: true,isSidebarMiddle: true,backgroundSize: 24,backgroundColor: Color.White,arrowSize: 18,arrowColor: Color.Blue}, false).curve(Curve.Linear).onChange((index: number) => {console.info(index.toString())}).onGestureSwipe((index: number, extraInfo: SwiperAnimationEvent) => {console.info("index: " + index)console.info("current offset: " + extraInfo.currentOffset)}).onAnimationStart((index: number, targetIndex: number, extraInfo: SwiperAnimationEvent) => {console.info("index: " + index)console.info("targetIndex: " + targetIndex)console.info("current offset: " + extraInfo.currentOffset)console.info("target offset: " + extraInfo.targetOffset)console.info("velocity: " + extraInfo.velocity)}).onAnimationEnd((index: number, extraInfo: SwiperAnimationEvent) => {console.info("index: " + index)console.info("current offset: " + extraInfo.currentOffset)})}.width('100%')}
}