Arkts框架Scroll组件基本使用
·
Scroll组件作为一个滚动展示内容的组件,在许多APP中都具有重要作用,下面来介绍一些Scroll组件的基本使用
@Entry
@Component
struct Index{
//创建Scroller 对象(实例化),控制滚动条的滚动
myScroll: Scroller = new Scroller()
@State arr: string[] = ["顶部","新建文本1","新建文本1","新建文本1","新建文本1","新建文本1","新建文本1","新建文本1","新建文本1","新建文本1","底部"]
build() {
Column({space:10}){
// 要给组件设置尺寸,Scroll组件里面只能有一个子组件,可以设置滚动方向,
Scroll(this.myScroll){
Column({space:20}){
ForEach(this.arr,(item: string,index: number)=>{
Text(item.toString())
.width('100%')
.height(100)
.backgroundColor('#00ffcc')
})
}
}
.onWillScroll((x,y)=>{
console.log('已经滑动的距离:',this.myScroll.currentOffset().xOffset,this.myScroll.currentOffset().yOffset)
})
.width('100%')
.height('50%')
.scrollable(ScrollDirection.Vertical)
.scrollBar(BarState.Auto) // On Off Auto
.scrollBarColor(Color.Blue)
.scrollBarWidth(5)
.edgeEffect(EdgeEffect.Spring) //弹簧效果
Button("控制滚动条位置").margin(20).onClick(()=>{
this.myScroll.scrollEdge(Edge.Top);
})
Button("控制滚动条位置").margin(20).onClick(()=>{
this.myScroll.scrollEdge(Edge.Bottom);
})
Button("获取已经滚动的距离").onClick(()=>{
const y = this.myScroll.currentOffset().yOffset
AlertDialog.show({
message:`y:${y}`
})
})
}
.width('100%')
.height('100%')
}
}
上面的是一个简单的Scroll组件展示,其中要注意的是:
1、必须给Scroll组件设置宽高,并且Scroll组件只能有一个子组件,如果要展示更多内容,可以在子组件之内再有子组件
2、.scrollable() 这个是设置滚动方向,
3、.scrollBar() 这个是控制滚动条的显示和隐藏,有三个属性:On(一直显示)、Off(一直隐藏)、Auto(滚动时显示)
4、.scrollBarColor() 这个是控制滚动条的颜色
5、.scrollBarWidth() 这个是控制滚动条的大小
6、.edgeEffect() 这个属性就比较重要了,控制滚动到底部或者顶部产生的效果,比如说Spring,我们最熟悉的弹簧效果,还有Fade(阴影效果)
7、控制组件的滚动位置,需要先在前面实例化Scroller对象,然后通过引用这个对象,就能将对象和组件联系在一起,我们只需要操作Scroller对象,就能控制组件的滚动效果
myScroll: Scroller = new Scroller()
Scroll(this.myScroll){
}
例如:
this.myScroll.scrollEdge(Edge.Top);
控制组件滚动到顶部
const y = this.myScroll.currentOffset().yOffset
AlertDialog.show({
message:`y:${y}`
})
获取当前滚动到底位置
8、滚动组件触发的函数,在新版本中可能已经弃用了onScroll()滚动函数,推荐大家用onWillScroll()
onWillScroll((x,y)=>{
console.log('已经滑动的距离:',this.myScroll.currentOffset().xOffset,this.myScroll.currentOffset().yOffset)
})
在滚动组件就会触发函数,执行操作
以上便是我对Scroll组件的理解,如果有不对的地方,可以提出纠正
更多推荐

所有评论(0)