需求
在开发中,使用滚动组件时,有时需要实现吸顶(Sticky)效果。在当前ArkTS中没有相应组件,所以我把我的实现代码分享出来
实现原理
结构【Stack组件】>【Scroll组件(吸顶组件占位)】+【吸顶目标Column】
在Scroll滚动时,记录当前总滚动值,并改变吸顶组件的外边距。当吸顶组件出滚动区域时,不再改变外边距即可
期望效果
吸顶效果
代码实现
@Entry
@ComponentV2
export struct Sticky {
searchHeight = 35
scroll0Height = 35 //吸顶组件上部分高度
stickyHeight = 35 //吸顶组件高度
scrollHeight = 500//模拟数据高度
@Local currYOffset: number = 0//当前Scroll竖向偏移量
scroller: Scroller = new Scroller()
aboutToAppear(): void {
this.scroller.scrollTo({ xOffset: 0, yOffset: this.currYOffset })
}
build() {
Column() {
Column() {
Text("[搜索框区域]")
}
.width('100%')
.height(this.searchHeight )
.backgroundColor("#999")
Stack() {
//滚动区
Scroll(this.scroller) {
Column() {
Column() {
Text("功能模块")
}
.width('100%')
.height(this.scroll0Height)
.backgroundColor('#999')
//吸顶组件占位
Column()
.height(this.stickyHeight)
Column()
.width('100%')
.height(this.scrollHeight)
.backgroundColor('#89a')
Column()
.width('100%')
.height(this.scrollHeight)
.backgroundColor('#9ab')
Column()
.width('100%')
.height(this.scrollHeight)
.backgroundColor('#abc')
}
.width('100%')
}
.width('100%')
.height('100%')
.edgeEffect(EdgeEffect.Spring)
.scrollable(ScrollDirection.Vertical)
.onWillScroll((x, y) => {
this.currYOffset += y
})
//筛选栏
Column() {
Text("筛选栏")
}
.width('100%')
.height(this.stickyHeight)
.backgroundColor('#700')
.margin({
top: this.scroll0Height - Math.min(this.currYOffset, this.scroll0Height)
})
}
.width('100%')
.layoutWeight(1)
.alignContent(Alignment.Top)
}
.width('100%')
.height('100%')
}
}