harmony 鸿蒙Swiper

  • 2022-08-09
  • 浏览 (900)

Swiper

The <Swiper> component is able to display child components in looping mode.

NOTE

This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.

Child Components

This component can contain child components.

NOTE

Built-in components and custom components are allowed, with support for (if/else, ForEach, and LazyForEach) rendering control.

When the <Swiper> component’s displayMode attribute is set to SwiperDisplayMode.AutoLinear or its displayCount attribute is set to ‘auto’, the child component whose visibility attribute is set to None does not take up space in the viewport, but this does not affect the number of navigation dots.

If the visibility attribute of a child component is set to None or Hidden, it takes up space in the viewport, but is not displayed.

When the number of child components is less than or equal to the total number of allowed nodes (totalDisplayCount = DisplayCount + prevMargin? (1: 0 ) + nextMargin? (1: 0 )) in the content area, the <Swiper> component uses the non-looping mode for layout. In this case, the child components specified by nextMargin and prevMargin take up space in the viewport, but are not displayed. The specifications of the <Swiper> component are calculated based on the value of totalDisplayCount.

APIs

Swiper(controller?: SwiperController)

Parameters

Name Type Mandatory Description
controller SwiperController No Controller bound to the component to control the page switching.

Attributes

In addition to the universal attributes, the following attributes are supported. Menu control is not supported.

Name Type Description
index number Index of the child component currently displayed in the container.
Default value: 0
NOTE
If the value is less than 0 or greater than or equal to the number of child components, the default value 0 is used.
Since API version 10, this attribute supports $$ for two-way binding of variables.
autoPlay boolean Whether to enable automatic playback for child component switching.
Default value: false
NOTE
If loop is set to false, the playback stops when the last page is displayed. The playback continues when the page is not the last page after a swipe gesture.
interval number Interval for automatic playback, in ms.
Default value: 3000
indicator10+ DotIndicator |DigitIndicator |boolean Style of the navigation point indicator.
- DotIndicator: dot style.
- DigitIndicator: digit style.
- boolean: whether to enable the navigation point indicator.
Default value: true
Default type: DotIndicator
loop boolean Whether to enable loop playback.
The value true means to enable loop playback. When LazyForEach is used, it is recommended that the number of the components to load exceed 5.
Default value: true
duration number Duration of the animation for switching child components, in ms.
Default value: 400
vertical boolean Whether vertical swiping is used.
Default value: false
itemSpace number |string Space between child components.
Default value: 0
NOTE
This parameter cannot be set in percentage.
displayMode SwiperDisplayMode Mode in which elements are displayed along the main axis. This attribute takes effect only when displayCount is not set.
Default value: SwiperDisplayMode.Stretch
cachedCount8+ number Number of child components to be cached.
Default value: 1
disableSwipe8+ boolean Whether to disable the swipe feature.
Default value: false
curve8+ Curve |string Animation curve. The ease-in/ease-out curve is used by default. For details about common curves, see Curve. You can also create custom curves (interpolation curve objects) by using the API provided by the interpolation calculation module.
Default value: Curve.Linear
indicatorStyle(deprecated) {
left?: Length,
top?: Length,
right?: Length,
bottom?: Length,
size?: Length,
mask?: boolean,
color?: ResourceColor,
selectedColor?: ResourceColor
}
Style of the navigation point indicator.
- left: distance between the navigation point indicator and the left edge of the <Swiper> component.
- top: distance between the navigation point indicator and the top edge of the <Swiper> component.
- right: distance between the navigation point indicator and the right edge of the <Swiper> component.
- bottom: distance between the navigation point indicator and the bottom edge of the <Swiper> component.
- size: diameter of the navigation point indicator. The value cannot be in percentage. Default value: 6vp
- mask: whether to enable the mask for the navigation point indicator.
- color: color of the navigation point indicator.
- selectedColor: color of the selected navigation dot.
This API is supported since API version 8 and is deprecated since API version 10. You are advised to use indicator instead.
displayCount8+ number |string |
SwiperAutoFill10+
Number of elements to display per page.
Default value: 1
NOTE
If the value is of the string type, it can only be ‘auto’, whose display effect is the same as that of SwiperDisplayMode.AutoLinear.
If the value is set to a number less than or equal to 0, the default value 1 is used.
If the value is of the number type, child components stretch (shrink) on the main axis after the swiper width [deducting the result of itemSpace x (displayCount - 1)] is evenly distributed among them on the main axis.
If the value is of the SwiperAutoFill type, the system automatically calculates and changes the number of elements to display per page based on the <Swiper> component width and the minSize settings for the child component. If minSize is left empty or set to a value less than or equal to 0, the <Swiper> component displays one column.
effectMode8+ EdgeEffect Effect when the component is at one of the edges. This parameter is effective only when loop is set to false. For details about the supported effects, see the EdgeEffect enums.
Default value: EdgeEffect.Spring
NOTE
The spring effect does not take effect when the controller API is called.
displayArrow10+ value:ArrowStyle |boolean,
isHoverShow?: boolean
Arrow style of the navigation point indicator.
- value: arrow and background to set. In abnormal scenarios, the default values in the ArrowStyle object are used.
- isHoverShow: whether to show the arrow only when the mouse pointer hovers over the navigation point indicator.
Default value: false
NOTE
When isHoverShow is set to false, the arrow is always displayed and can be clicked to turn pages.
When isHoverShow is set to true, the arrow is displayed only when the mouse pointer hovers over the navigation point indicator, and it can be clicked to turn pages.
nextMargin10+
Length
Next margin, used to reveal a small part of the next item.
Default value: 0
NOTE
This attribute is available only when SwiperDisplayMode is set to STRETCH.
When the main axis runs horizontally and either the next margin or previous margin is greater than the calculated width of the child component, neither the next margin nor previous margin is displayed.
When the main axis runs vertically and either the next margin or previous margin is greater than the calculated height of the child component, neither the next margin nor previous margin is displayed.
prevMargin10+
Length
Previous margin, used to reveal a small part of the previous item.
Default value: 0
NOTE
This attribute is available only when SwiperDisplayMode is set to STRETCH.
When the main axis runs horizontally and either the next margin or previous margin is greater than the calculated width of the child component, neither the next margin nor previous margin is displayed.
When the main axis runs vertically and either the next margin or previous margin is greater than the calculated height of the child component, neither the next margin nor previous margin is displayed.

SwiperDisplayMode

Name Description
Stretch(deprecated) The slide width of the <Swiper> component is equal to the width of the component.
This API is deprecated since API version 10. You are advised to use STRETCH instead.
AutoLinear(deprecated) The slide width of the <Swiper> component is equal to that of the child component with the maximum width.
This API is deprecated since API version 10. You are advised to use AUTO_LINEAR instead.
STRETCH10+ The slide width of the <Swiper> component is equal to the width of the component.
AUTO_LINEAR10+ The slide width of the <Swiper> component is equal to the width of the leftmost child component in the viewport.

SwiperController

Controller of the <Swiper> component. You can bind this object to the <Swiper> component and use it to control page switching.

showNext

showNext(): void

Turns to the next page. Page turning occurs with the animation, whose duration is specified by duration.

showPrevious

showPrevious(): void

Turns to the previous page. Page turning occurs with the animation, whose duration is specified by duration.

finishAnimation

finishAnimation(callback?: () => void): void

Stops an animation.

Parameters

Name Type Mandatory. Description
callback () => void No Callback invoked when the animation stops.

Indicator10+

Sets the distance between the navigation point indicator and the <Swiper> component.

Name Type Mandatory. Description
left Length No Distance between the navigation point indicator and the left edge of the <Swiper> component.
Default value: 0
Unit: vp
top Length No Distance between the navigation point indicator and the top edge of the <Swiper> component.
Default value: 0
Unit: vp
right Length No Distance between the navigation point indicator and the right edge of the <Swiper> component.
Default value: 0
Unit: vp
bottom Length No Distance between the navigation point indicator and the bottom edge of the <Swiper> component.
Default value: 0
Unit: vp

DotIndicator10+

Defines the navigation point indicator of the dot style, which inherits attributes and features from Indicator.

Name Type Mandatory. Description
itemWidth Length No Width of the navigation point indicator of the dot style. This parameter cannot be set in percentage.
Default value: 6
Unit: vp
itemHeight Length No Height of the navigation point indicator of the dot style. This parameter cannot be set in percentage.
Default value: 6
Unit: vp
selectedItemWidth Length No Width of the selected navigation point indicator of the dot style. This parameter cannot be set in percentage.
Default value: 12
Unit: vp
selectedItemHeight Length No Height of the selected navigation point indicator of the dot style. This parameter cannot be set in percentage.
Default value: 6
Unit: vp
mask boolean No Whether to enable the mask for the navigation point indicator of the dot style.
Default value: false
color ResourceColor No Color of the navigation point indicator of the dot style.
Default value: ‘#182431’ (10% opacity)
selectedColor ResourceColor No Color of the selected indicator dot.
Default value: ‘#007DFF’

DigitIndicator10+

Defines the navigation point indicator of the digit style, which inherits attributes and features from Indicator.

Name Type Mandatory. Description
fontColor ResourceColor No Font color of the navigation point indicator of the digit style.
Default value: ‘#ff182431’
selectedFontColor ResourceColor No Font color of the selected navigation point indicator of the digit style.
Default value: ‘#ff182431’
digitFont {
size?:Length
weight?:number |FontWeight |string
}
No Font style of the navigation point indicator of the digit style.
- size:font size. It cannot be set in percentage.
Default value: 14vp
- weight: font weight.
selectedDigitFont {
size?:Length
weight?:number |FontWeight |string
}
No Font style of the selected navigation point indicator of the digit style.
- size:font size. It cannot be set in percentage.
Default value: 14vp
- weight: font weight.

ArrowStyle10+

Describes the left and right arrow attributes.

Name Type Mandatory. Description
showBackground boolean No Whether to show the background for the arrow.
Default value: false
isSidebarMiddle boolean No Whether the arrow is shown on either side of the navigation point indicator.
Default value: false (the arrow is shown on either side of the navigation point indicator)
backgroundSize Length No Size of the background.
On both sides of the navigation point indicator:
Default value: 24vp
On both sides of the component:
Default value: 32vp
This parameter cannot be set in percentage.
backgroundColor ResourceColor No Color of the background.
On both sides of the navigation point indicator:
Default value: ‘#00000000’
On both sides of the component:
Default value: ‘#19182431’
arrowSize Length No Size of the arrow.
On both sides of the navigation point indicator:
Default value: 18vp
On both sides of the component:
Default value: 24vp
NOTE
If showBackground is set to true, the value of arrowSize is 34 of the value of backgroundSize.
This parameter cannot be set in percentage.
arrowColor ResourceColor No Color of the arrow.
Default value: ‘#182431’

SwiperAutoFill10+

Describes the auto-fill attribute.

Name Type Mandatory. Description
minSize VP Yes Minimum width of the element.
Default value: 0

Events

In addition to the universal events, the following events are supported.

Name Description
onChange(event: (index: number) => void) Triggered when the index of the currently displayed child component changes.
- index: index of the currently displayed element.
NOTE
When the <Swiper> component is used together with LazyForEach, the subpage UI update cannot be triggered in the onChange event.
onAnimationStart9+(event: (index: number, targetIndex10+: number, extraInfo10+: SwiperAnimationEvent) => void) Triggered when the switching animation starts.
- index: index of the currently displayed element.
- targetIndex: index of the target element to switch to.
- extraInfo: extra information of the animation, including the offset of the currently displayed element and target element relative to the start position of the <Swiper> along the main axis, and the hands-off velocity.
NOTE
The index parameter indicates the index before the animation starts (not the one after). When the <Swiper> component contains multiple columns, the index is of the leftmost element.
onAnimationEnd9+(event: (index: number, extraInfo: SwiperAnimationEvent) => void) Triggered when the switching animation ends.
- index: index of the currently displayed element.
- extraInfo: extra information of the animation, which is the offset of the currently displayed element relative to the start position of the <Swiper> along the main axis.
NOTE
This event is triggered when the switching animation of the <Swiper> component ends, whether it is caused by gesture interruption or by calling finishAnimation through SwiperController. The index parameter indicates the index after the animation ends. When the <Swiper> component contains multiple columns, the index is of the leftmost element.
onGestureSwipe10+(event: (index: number, extraInfo: SwiperAnimationEvent) => void) Triggered on a frame-by-frame basis when the page is turned by a swipe.
- index: index of the currently displayed element.
- extraInfo: extra information of the animation, which is the offset of the currently displayed element relative to the start position of the <Swiper> along the main axis.
NOTE
If there are multiple columns, index indicates the index of the leftmost component.

Example

Example 1

// xxx.ets
class MyDataSource implements IDataSource {
  private list: number[] = []

  constructor(list: number[]) {
    this.list = list
  }

  totalCount(): number {
    return this.list.length
  }

  getData(index: number): number {
    return this.list[index]
  }

  registerDataChangeListener(listener: DataChangeListener): void {
  }

  unregisterDataChangeListener() {
  }
}

@Entry
@Component
struct SwiperExample {
  private swiperController: SwiperController = new SwiperController()
  private data: MyDataSource = new MyDataSource([])

  aboutToAppear(): void {
    let list: number[] = []
    for (let i = 1; i <= 10; i++) {
      list.push(i);
    }
    this.data = new MyDataSource(list)
  }

  build() {
    Column({ space: 5 }) {
      Swiper(this.swiperController) {
        LazyForEach(this.data, (item: string) => {
          Text(item.toString())
            .width('90%')
            .height(160)
            .backgroundColor(0xAFEEEE)
            .textAlign(TextAlign.Center)
            .fontSize(30)
        }, (item: string) => item)
      }
      .cachedCount(2)
      .index(1)
      .autoPlay(true)
      .interval(4000)
      .indicator(true)
      .loop(true)
      .duration(1000)
      .itemSpace(0)
      .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)
      })

      Row({ space: 12 }) {
        Button('showNext')
          .onClick(() => {
            this.swiperController.showNext()
          })
        Button('showPrevious')
          .onClick(() => {
            this.swiperController.showPrevious()
          })
      }.margin(5)
    }.width('100%')
    .margin({ top: 5 })
  }
}

swiper

Example 2

// xxx.ets
class MyDataSource implements IDataSource {
  private list: number[] = []

  constructor(list: number[]) {
    this.list = list
  }

  totalCount(): number {
    return this.list.length
  }

  getData(index: number): number {
    return this.list[index]
  }

  registerDataChangeListener(listener: DataChangeListener): void {
  }

  unregisterDataChangeListener() {
  }
}

@Entry
@Component
struct SwiperExample {
  private swiperController: SwiperController = new SwiperController()
  private data: MyDataSource = new MyDataSource([])

  aboutToAppear(): void {
    let list: number[] = []
    for (let i = 1; i <= 10; i++) {
      list.push(i);
    }
    this.data = new MyDataSource(list)
  }

  build() {
    Column({ space: 5 }) {
      Swiper(this.swiperController) {
        LazyForEach(this.data, (item: string) => {
          Text(item.toString())
            .width('90%')
            .height(160)
            .backgroundColor(0xAFEEEE)
            .textAlign(TextAlign.Center)
            .fontSize(30)
        }, (item: string) => item)
      }
      .cachedCount(2)
      .index(1)
      .autoPlay(true)
      .interval(4000)
      .indicator(Indicator.dot()
        .itemWidth(15)
        .itemHeight(15)
        .selectedItemWidth(15)
        .selectedItemHeight(15)
        .color(Color.Gray)
        .selectedColor(Color.Blue))
      .loop(true)
      .duration(1000)
      .itemSpace(0)
      .displayArrow(true, true)

      Row({ space: 12 }) {
        Button('showNext')
          .onClick(() => {
            this.swiperController.showNext()
          })
        Button('showPrevious')
          .onClick(() => {
            this.swiperController.showPrevious()
          })
      }.margin(5)
    }.width('100%')
    .margin({ top: 5 })
  }
}

swiper

Example 3

// xxx.ets
class MyDataSource implements IDataSource {
  private list: number[] = []

  constructor(list: number[]) {
    this.list = list
  }

  totalCount(): number {
    return this.list.length
  }

  getData(index: number): number {
    return this.list[index]
  }

  registerDataChangeListener(listener: DataChangeListener): void {
  }

  unregisterDataChangeListener() {
  }
}

@Entry
@Component
struct SwiperExample {
  private swiperController: SwiperController = new SwiperController()
  private data: MyDataSource = new MyDataSource([])

  aboutToAppear(): void {
    let list: number[] = []
    for (let i = 1; i <= 10; i++) {
      list.push(i);
    }
    this.data = new MyDataSource(list)
  }

  build() {
    Column({ space: 5 }) {
      Swiper(this.swiperController) {
        LazyForEach(this.data, (item: string) => {
          Text(item.toString())
            .width('90%')
            .height(160)
            .backgroundColor(0xAFEEEE)
            .textAlign(TextAlign.Center)
            .fontSize(30)
        }, (item: string) => item)
      }
      .cachedCount(2)
      .index(1)
      .autoPlay(true)
      .interval(4000)
      .indicator(Indicator.digit()
        .right("43%")
        .top(200)
        .fontColor(Color.Gray)
        .selectedFontColor(Color.Gray)
        .digitFont({ size: 20, weight: FontWeight.Bold })
        .selectedDigitFont({ size: 20, weight: FontWeight.Normal }))
      .loop(true)
      .duration(1000)
      .itemSpace(0)
      .displayArrow(true, false)

      Row({ space: 12 }) {
        Button('showNext')
          .onClick(() => {
            this.swiperController.showNext()
          })
        Button('showPrevious')
          .onClick(() => {
            this.swiperController.showPrevious()
          })
      }.margin(5)
    }.width('100%')
    .margin({ top: 5 })
  }
}

swiper

你可能感兴趣的鸿蒙文章

harmony 鸿蒙ArkTS-based Declarative Development Paradigm

harmony 鸿蒙@ohos.multimedia.avCastPicker (AVCastPicker)

harmony 鸿蒙Property Animation

harmony 鸿蒙Enums

harmony 鸿蒙Blank

harmony 鸿蒙Button

harmony 鸿蒙CalendarPicker

harmony 鸿蒙Checkbox

harmony 鸿蒙CheckboxGroup

harmony 鸿蒙DataPanel

0  赞