
回复
Scroll,其实就是一个“能滚动的容器”,你可以把它理解成 ArkTS 里的万能滚动盒子。只要你的内容超出了父容器的空间,Scroll就能自动出现滚动条,帮你把内容滑进视野里。
使用场景举例
很多时候我们用Scroll只是为了装一大堆内容,让它能滚动起来。下面是最基础的代码示例。
@Entry
@Component
struct SimpleScrollDemo {
private items: string[] = [];
onLoad() {
for (let i = 0; i < 20; i++) {
this.items.push(`内容 ${i + 1}`);
}
}
build() {
Scroll() {
Column() {
ForEach(this.items, (item: string) => {
Text(item)
.width('90%')
.padding(16)
.margin({ top: 8, bottom: 8 })
.backgroundColor(0xF8F8F8)
.borderRadius(8)
.fontSize(17)
})
}
.width('100%')
}
.height('75%')
.backgroundColor('#F2F3F5')
.scrollBar(BarState.On)
}
}
说明:
Scroll 支持指定滚动方向,不止竖直滚动,水平/双向都可以用!
@Entry
@Component
struct DirectionScrollDemo {
private imgs: string[] = ['A', 'B', 'C', 'D', 'E', 'F']
build() {
Column() {
// 横向滚动内容
Scroll() {
Row() {
ForEach(this.imgs, (item: string) => {
Text('图片' + item)
.width(120)
.height(100)
.fontSize(24)
.backgroundColor('#BBDEFB')
.textAlign(TextAlign.Center)
.margin({ right: 18 })
.borderRadius(14)
})
}
.height(100)
.padding({ left: 12 })
}
.scrollable(ScrollDirection.Horizontal)
.height(120)
.backgroundColor('#E3F2FD')
}
.width('100%') // 确保根容器宽度撑满
}
}
技巧:
想让滚动条“更明显”,或者跟界面风格一致,可以用这些方法:
@Entry
@Component
struct CustomScrollbarDemo {
build() {
Scroll()
.scrollable(ScrollDirection.Vertical)
.scrollBar(BarState.On)
.scrollBarColor('#007AFF')
.scrollBarWidth(8) {
Column() {
ForEach(Array.from({length: 30}, (_, i) => i + 1), (idx: number) => {
Text(`Item #${idx}`)
.width('92%')
.height(60)
.margin({ bottom: 8 })
.backgroundColor('#E5F3FF')
.borderRadius(12)
.fontSize(17)
})
}
.width('100%')
.padding({ top: 16 })
}
.height('70%')
.backgroundColor('#E0F7FA')
}
}
说明:
Scroll 不只是让用户用手滑,还可以用代码精确控制滚动,比如自动回到顶部、滚动到底部、跳转到指定位置等。
@Entry
@Component
struct ScrollControlDemo {
scroller: Scroller = new Scroller()
build() {
Column({ space: 12 }) {
// 滚动区域
Scroll() {
Column() {
// 使用 ForEach 构建列表项
ForEach(
Array.from({ length: 16 }, (_: number, i: number) => `内容${i + 1}`),
(item: string) => {
Text(item)
.width('95%')
.padding(14)
.backgroundColor(0xE2E6EF)
.fontSize(16)
.borderRadius(9)
.margin({ top: 5, bottom: 5 })
}
)
}
.width('100%')
}
.scrollable(ScrollDirection.Vertical) // 设置垂直滚动
.height(260) // 设置滚动区域高度
// 滚动控制按钮
Row({ space: 18 }) {
Button('回到顶部')
.onClick(() => {
this.scroller.scrollTo({ xOffset: 0, yOffset: 0, animation: true })
})
Button('滚动到底部')
.onClick(() => {
this.scroller.scrollEdge(Edge.Bottom)
})
Button('下移120')
.onClick(() => {
this.scroller.scrollBy(0, 120)
})
}
}
.padding(18)
.backgroundColor('#F7F8FA') // 页面背景色
.width('100%')
.height('100%')
}
}
Scroll 是 ArkTS UI 里最基础的“滚动容器”,但它的功能非常丰富,能轻松适配从单纯竖直滚动、横向滚动、嵌套滚动,到惯性回弹、分页翻页、各种滚动监听与自定义手势控制。
建议你多尝试自定义 Demo,实际动手测试各类属性和事件,体验滚动细节的可控性。
有任何实战难题、性能疑问或者用法拓展,也欢迎在评论区一起交流!