
回复
日常开发过程中,遇到这种 Scroll 嵌套 List 列表滑动顶部悬停的场景十分常见,在鸿蒙开发时也正好实现了这个功能,本篇文章将带你一步步实现 Tab 顶部悬停的效果,建议点赞收藏!
先看本文的最终实现效果如下:
Scroll(this.scroller) {
Column() {
Text("内容")
.textAlign(TextAlign.Center)
.fontColor(Color.White)
.backgroundColor(this.themColor.value)
.width('100%')
.height('40%')
Tabs({ barPosition: BarPosition.Start }) {
TabContent() {
Column() {
Refresh({refreshing:false,friction:0,offset:0}){
List({ space: 10, scroller: this.scrollerForList }) {
ForEach(this.list, (item: string) => {
ListItem() {
Text('ListItem' + item)
.width('100%')
.height('100%')
.borderRadius(15)
.fontSize(24)
.textAlign(TextAlign.Center)
.backgroundColor(Color.White)
}
.width('100%')
.height(100)
}, (item: string) => item)
}
.pullToRefresh(true)
}
}.tabBar('你好')
TabContent() {
Column().width('100%').height('100%').backgroundColor('#007DFF')
}.tabBar('好的')
}
}
这里布局比较简单,使用两个 tab 用来切换布局。外层使用 Scroll 包裹,其中一个 tab 的里面使用 List 布局。相信这对大多人来说没有什么难度。
.nestedScroll({
scrollForward: NestedScrollMode.PARENT_FIRST,
scrollBackward: NestedScrollMode.PARENT_FIRST
})
enum ScrollPosition {
top,
center,
bottom
}
.onReachStart(() => {
this.listPosition = ScrollPosition.top
})
.onReachEnd(() => {
this.listPosition = ScrollPosition.bottom
})
.onScrollFrameBegin((offset: number, state: ScrollState) => {
if ((this.listPosition == ScrollPosition.top && offset <=0)||(this.listPosition == ScrollPosition.bottom && offset>=0)) {
return {offsetRemain :offset}
}
this.listPosition = ScrollPosition.center
return {offsetRemain:offset}
})
.onReachStart(() => {
this.listPosition = ScrollPosition.top
})
.onReachEnd(() => {
this.listPosition = ScrollPosition.bottom
})
.onScrollFrameBegin((offset: number, _: ScrollState) => {
if ((this.listPosition == ScrollPosition.top && offset <= 0) || (
this.listPosition == ScrollPosition.bottom && offset >= 0)
) {
return { offsetRemain: 0 }
}
//不在底部
this.listPosition = ScrollPosition.center
return { offsetRemain: offset }
})
本文主要是根据实际需求实现的滑动效果,每次都优先让 Scroll 滑动,还有更多的滑动场景都可以用这种方式的思路解决,主要通过不同的判断条件即可实现。例如向下滑动时优先让 List 滑动,然后再让 Scroll 滑动。学会的小伙伴赶紧动手试试吧!