• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Swiper
2
3 The **\<Swiper>** component is able to display child components in looping mode.
4
5> **NOTE**
6>
7> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
8
9
10## Child Components
11
12This component can contain child components.
13
14>  **NOTE**
15>
16>  Built-in components and custom components are allowed, with support for ([if/else](../../quick-start/arkts-rendering-control-ifelse.md), [ForEach](../../quick-start/arkts-rendering-control-foreach.md), and [LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md)) rendering control.
17>
18>  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.
19>
20>  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.
21
22
23## APIs
24
25Swiper(controller?: SwiperController)
26
27**Parameters**
28
29| Name       | Type                          | Mandatory | Description                |
30| ---------- | ------------------------------------- | ---- | -------------------- |
31| controller | [SwiperController](#swipercontroller) | No  | Controller bound to the component to control the page switching.|
32
33
34## Attributes
35
36In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. [Menu control](ts-universal-attributes-menu.md) is not supported.
37
38| Name                         | Type                              | Description                                      |
39| --------------------------- | ---------------------------------------- | ---------------------------------------- |
40| index                       | number                                   | Index of the child component currently displayed in the container.<br>Default value: **0**<br>**NOTE**<br>If the value is less than 0 or greater than or equal to the number of child components, the default value **0** is used.|
41| autoPlay                    | boolean                                  | Whether to enable automatic playback for child component switching.<br>Default value: **false**<br>**NOTE**<br>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.|
42| interval                    | number                                   | Interval for automatic playback, in ms.<br>Default value: **3000**                   |
43| indicator                   | boolean                                  | Whether to enable the navigation dots indicator.<br>Default value: **true**                             |
44| loop                        | boolean                                  | Whether to enable loop playback.<br>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.<br>Default value: **true**|
45| duration                    | number                                   | Duration of the animation for switching child components, in ms.<br>Default value: **400**                       |
46| vertical                    | boolean                                  | Whether vertical swiping is used.<br>Default value: **false**                                |
47| itemSpace                   | number \| string          | Space between child components.<br>Default value: **0**<br>**NOTE**<br>This parameter cannot be set in percentage.|
48| displayMode                 | SwiperDisplayMode                        | Mode in which elements are displayed along the main axis. This attribute takes effect only when **displayCount** is not set.<br>Default value: **SwiperDisplayMode.Stretch**|
49| cachedCount<sup>8+</sup>              | number                                   | Number of child components to be cached.<br>Default value: **1**<br>**NOTE**<br>This attribute applies only when the **\<Swiper>** component uses [LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md).|
50| disableSwipe<sup>8+</sup>   | boolean                                  | Whether to disable the swipe feature.<br>Default value: **false**                             |
51| curve<sup>8+</sup>          | [Curve](ts-appendix-enums.md#curve)  \| string | Animation curve. The ease-in/ease-out curve is used by default. For details about common curves, see [Curve](ts-appendix-enums.md#curve). You can also create custom curves (interpolation curve objects) by using the API provided by the [interpolation calculation](../apis/js-apis-curve.md) module.<br>Default value: **Curve.Linear**|
52| indicatorStyle<sup>8+</sup> | {<br>left?: [Length](ts-types.md#length),<br>top?: [Length](ts-types.md#length),<br>right?: [Length](ts-types.md#length),<br>bottom?: [Length](ts-types.md#length),<br>size?: [Length](ts-types.md#length),<br>mask?: boolean,<br>color?: [ResourceColor](ts-types.md),<br>selectedColor?: [ResourceColor](ts-types.md)<br>} | Style of the navigation point indicator.<br>\- **left**: distance between the navigation point indicator and the left edge of the **\<Swiper>** component.<br>\- **top**: distance between the navigation point indicator and the top edge of the **\<Swiper>** component.<br>\- **right**: distance between the navigation point indicator and the right edge of the **\<Swiper>** component.<br>\- **bottom**: distance between the navigation point indicator and the bottom edge of the **\<Swiper>** component.<br>\- **size**: diameter of the navigation point indicator. The value cannot be in percentage. Default value: **6vp**<br>\- **mask**: whether to enable the mask for the navigation point indicator.<br>\- **color**: color of the navigation point indicator.<br>\- **selectedColor**: color of the selected navigation dot.|
53| displayCount<sup>8+</sup>   | number \| string | Number of elements to display per page.<br>Default value: **1**<br>**NOTE**<br>If the value is of the string type, it can only be **'auto'**, whose display effect is the same as that of **SwiperDisplayMode.AutoLinear**.<br>If the value is set to a number less than or equal to 0, the default value **1** is used.<br>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.|
54| effectMode<sup>8+</sup>     | [EdgeEffect](ts-appendix-enums.md#edgeeffect)  | Swipe effect. For details, see **EdgeEffect**.<br>Default value: **EdgeEffect.Spring**<br>**NOTE**<br>The spring effect does not take effect when the controller API is called.|
55
56## SwiperDisplayMode
57
58| Name| Description|
59| ----------- | ------------------------------------------ |
60| Stretch     | The slide width of the **\<Swiper>** component is equal to the width of the component.|
61| AutoLinear  | The slide width of the **\<Swiper>** component is equal to that of the child component with the maximum width.|
62
63## SwiperController
64
65Controller of the **\<Swiper>** component. You can bind this object to the **\<Swiper>** component and use it to control page switching.
66
67### showNext
68
69showNext(): void
70
71Turns to the next page. Page turning occurs with the animation, whose duration is specified by **duration**.
72
73### showPrevious
74
75showPrevious(): void
76
77Turns to the previous page. Page turning occurs with the animation, whose duration is specified by **duration**.
78
79### finishAnimation
80
81finishAnimation(callback?: () => void): void
82
83Stops an animation.
84
85**Parameters**
86
87| Name   | Type  | Mandatory.| Description|
88| --------- | ---------- | ------ | -------- |
89| callback  | () => void | No    | Callback invoked when the animation stops.|
90
91
92## Events
93
94In addition to the [universal events](ts-universal-events-click.md), the following events are supported.
95
96| Name                                                        | Description                                                    |
97| ------------------------------------------------------------ | ------------------------------------------------------------ |
98| onChange(event: (index: number) => void)                     | Triggered when the index of the currently displayed child component changes.<br>- **index**: index of the currently displayed element.<br>**NOTE**<br>When the **\<Swiper>** component is used together with **LazyForEach**, the subpage UI update cannot be triggered in the **onChange** event.|
99| onAnimationStart<sup>9+</sup>(event: (index: number) => void) | Triggered when the switching animation starts.<br>- **index**: index of the currently displayed element.<br>**NOTE**<br>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.|
100| onAnimationEnd<sup>9+</sup>(event: (index: number) => void)  | Triggered when the switching animation ends.<br>- **index**: index of the currently displayed element.<br>**NOTE**<br>This event is triggered when the animation ends regardless of whether it is due to a user gesture or invocation of **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.|
101
102## Example
103
104```ts
105// xxx.ets
106class MyDataSource implements IDataSource {
107  private list: number[] = []
108  private listener: DataChangeListener
109
110  constructor(list: number[]) {
111    this.list = list
112  }
113
114  totalCount(): number {
115    return this.list.length
116  }
117
118  getData(index: number): any {
119    return this.list[index]
120  }
121
122  registerDataChangeListener(listener: DataChangeListener): void {
123    this.listener = listener
124  }
125
126  unregisterDataChangeListener() {
127  }
128}
129
130@Entry
131@Component
132struct SwiperExample {
133  private swiperController: SwiperController = new SwiperController()
134  private data: MyDataSource = new MyDataSource([])
135
136  aboutToAppear(): void {
137    let list = []
138    for (var i = 1; i <= 10; i++) {
139      list.push(i.toString());
140    }
141    this.data = new MyDataSource(list)
142  }
143
144  build() {
145    Column({ space: 5 }) {
146      Swiper(this.swiperController) {
147        LazyForEach(this.data, (item: string) => {
148          Text(item).width('90%').height(160).backgroundColor(0xAFEEEE).textAlign(TextAlign.Center).fontSize(30)
149        }, item => item)
150      }
151      .cachedCount(2)
152      .index(1)
153      .autoPlay(true)
154      .interval(4000)
155      .indicator(true)
156      .loop(true)
157      .duration(1000)
158      .itemSpace(0)
159      .curve(Curve.Linear)
160      .onChange((index: number) => {
161        console.info(index.toString())
162      })
163
164      Row({ space: 12 }) {
165        Button('showNext')
166          .onClick(() => {
167            this.swiperController.showNext()
168          })
169        Button('showPrevious')
170          .onClick(() => {
171            this.swiperController.showPrevious()
172          })
173      }.margin(5)
174    }.width('100%')
175    .margin({ top: 5 })
176  }
177}
178```
179
180![swiper](figures/swiper.gif)
181