Read the original article:How to Display the Page of a Specified Index in Swiper?
Problem Description
How to implement the Swiper component so that the last position's content is loaded upon initialization?
Background Knowledge
The Swiper component is a commonly used carousel component in ArkUI. For the Swiper component, the index attribute is provided, which can be used to set the default index value when the Swiper is displayed. If this attribute is not set, the content at the 0th position will be displayed by default.
For more information about the index attribute, please refer to: The index property of Swiper.. This attribute supports $$ two-way binding variables.
Solution
By using $$, the index property is bidirectionally bound to the variable decorated with @State.
- When you swipe the Swiper to switch pages, the index changes are synchronized to the @State variable, so that the index of the currently displayed page can be obtained.
- You can change the @State variable to change the page displayed by Swiper, and display the page with the specified index.
The sample code is as follows: Bind the @State variable showIndex to the index of Swiper in two-way mode.
@Entry
@Component
struct SwiperIndexDemo {
private swiperNumber: number[] = [0, 1, 2, 3, 4, 5, 6, 7];
@State showIndex: number = this.swiperNumber.length - 1;
private swiperController: SwiperController = new SwiperController();
build() {
Column({ space: 16 }) {
Swiper(this.swiperController) {
ForEach(this.swiperNumber, (item: number) => {
Text(item.toString())
.width(250)
.height(250)
.backgroundColor(Color.Gray)
.textAlign(TextAlign.Center)
.fontSize(30);
});
}.index($$this.showIndex); // Two-way binding with the showIndex variable.
Text(`Current showIndex:
${this.showIndex}`);
Button(`showIndex+1`)
.onClick(() => {
this.showIndex = (this.showIndex + 1) % this.swiperNumber.length;
});
}.width('100%').margin({ top: 5 });
}
}
The effect is as follows: The Swiper displays the content of the last page during initialization. Swiping the Swiper changes the value of showIndex, and changing the value of showIndex also enables you to swipe the Swiper.
FAQs
Q: The index method of Swiper shows that there is no sliding animation at the specified position. It is expected to be consistent with the manual sliding animation.
A: You can use the changeIndex method of SwiperController to specify the display position. By passing parameters, you can specify the animation effect for the transition.
Q: The ArcSwiper does not have the changeIndex method. How can I go to a specified page?
A: You can set the index attribute to go to a specified page.

Top comments (0)