鸿蒙Swiper实现加载更多,无更多数据控件
主要是通过onTouch事件实现的直接上代码自定义加载控件跟swiper解耦。import { YcRefreshNoMore, YcRefreshFooterLoading, STATE_LOAD_LOADING, STATE_STATE_FREE } from yiche/common Component export struct SwiperRefreshLayout { BuilderParam swiperComponent: () void Link hasMore: boolean Link isLastPosition: boolean Prop isSupportLoadMore: boolean true Link Watch(monitorLoadStatus) loadStatus: number onLoading?: () void //内部变量 static MAX_OFFSET -80 State pullOffset: number 0 downY: number -1 tempY: number -1 build() { Column() { Stack() { this.swiperComponent() } .width(100%) .height(100%) if (this.isSupportNoMoreCondition()) { YcRefreshNoMore() } else if (this.isSupportLoadMoreCondition()) { YcRefreshFooterLoading() } } .alignItems(HorizontalAlign.Start) .justifyContent(FlexAlign.Start) .width(100%) .height(100%) .margin({ top: this.pullOffset }) .offset({ y: this.pullOffset }) .position({ y: this.pullOffset }) .onTouch((event: TouchEvent) { if (this.loadStatus ! STATE_STATE_FREE) { return } if (this.isSupportNoMoreCondition() || this.isSupportLoadMoreCondition()) { switch (event.type) { case TouchType.Down: if (event.touches event.touches.length 0) { this.downY event.touches[0].y } else { this.resetDownEvent() } break case TouchType.Move: if (this.downY 0) { if (this.isSupportNoMoreCondition()) { if (event.touches event.touches.length 0) { this.tempY event.touches[0].y - this.downY if (this.downY 0 this.tempY 0) { this.pullOffset this.tempY SwiperRefreshLayout.MAX_OFFSET ? SwiperRefreshLayout.MAX_OFFSET : this.tempY } else { this.pullOffset 0 } } } else if (this.isSupportLoadMoreCondition()) { if (event.touches event.touches.length 0) { this.tempY event.touches[0].y - this.downY if (this.downY 0 this.tempY -30) { animateTo({ duration: 300, curve: Curve.LinearOutSlowIn }, () { this.pullOffset SwiperRefreshLayout.MAX_OFFSET this.onLoading?.() }) this.loadStatus STATE_LOAD_LOADING this.resetDownEvent() } else { this.pullOffset 0 } } } } break case TouchType.Up: case TouchType.Cancel: if (this.isSupportNoMoreCondition()) { this.resetBottomViewAnimation() } this.resetDownEvent() break } } }) } monitorLoadStatus() { if (this.loadStatus STATE_STATE_FREE) { setTimeout(() { this.resetBottomViewAnimation() }, 500) } } resetBottomViewAnimation() { animateTo({ duration: 300, curve: Curve.LinearOutSlowIn }, () { this.pullOffset 0 }) } resetDownEvent() { this.downY -1 this.tempY -1 } /** * 是否支持没有更多条件 * returns */ isSupportNoMoreCondition() { return !this.hasMore this.isLastPosition } /** * 是否支持加载更多条件 * returns */ isSupportLoadMoreCondition() { return this.isSupportLoadMore this.hasMore this.isLastPosition } }下面是使用示例SwiperRefreshLayout({ //分页是否还有更多 hasMore: this.haveMore, //是否是swiper最后一条 isLastPosition: this.isLastPosition, isSupportLoadMore: true, //加载状态自己定义几个常量即可 loadStatus: this.loadStatus, swiperComponent: () { //this.swiperContentView() //这里放swiper控件 }, onLoading: () { //加载更多 } })