HarmonyOS鸿蒙Next中scroll选中滚动居中
HarmonyOS鸿蒙Next中scroll选中滚动居中
scroll(){ row(){ foreach(数据源,()=>{布局builder}) } }
在scroll中如何点击某一项使其滚动到合适的位置,能滚动到中间的就滚动到中间,靠近两边的就使scroll滚动到相应边缘
2 回复
开发者你好,为更好的解决你的问题,需要你这边提供下更详细的ui效果图,动图最好。
下面有个代码案例,不太清楚是否符合你的要求,如果不符合要求,建议提供下完整的ui效果图 文字描述可能不是很好理解
@Entry
@Component
struct Index {
scroller: Scroller = new Scroller;
private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
@State itemHeights: number[] = new Array(16).fill(200)
private containerHeight: number = 800
build() {
Scroll(this.scroller) {
Column() {
ForEach(this.arr, (item: number, index) => {
Text(item.toString())
.width('90%')
.height(200)
.backgroundColor(0xFFFFFF)
.borderWidth(1)
.borderColor(Color.Black)
.borderRadius(15)
.fontSize(16)
.textAlign(TextAlign.Center)
.onClick(() => {
this.scrollToTarget(index)
})
}, (item: string) => item)
}.width('100%').backgroundColor(0xDCDCDC)
}
.backgroundColor(Color.Yellow)
.height(this.containerHeight)
.edgeEffect(EdgeEffect.Spring)
.scrollSnap({snapAlign:ScrollSnapAlign.CENTER, snapPagination: 100})
}
scrollToTarget(clickIndex: number) {
// 计算累计偏移量
let totalOffset = 0;
for (let i = 0; i < clickIndex; i++) {
totalOffset += this.itemHeights[i] || 0;
}
// 判断目标位置是否在中间区域
const targetMiddle = totalOffset + (this.itemHeights[clickIndex] / 2);
const visibleStart = this.scroller.currentOffset().yOffset
const visibleEnd = visibleStart + this.containerHeight;
if (targetMiddle > visibleStart + 100 && targetMiddle < visibleEnd - 100) {
// 无需滚动(已在可视区)
return;
} else if (clickIndex === 0) {
this.scroller.scrollEdge(Edge.Top); // 滚动到顶部
} else if (clickIndex === this.itemHeights.length - 1) {
this.scroller.scrollEdge(Edge.Bottom); // 滚动到底部
} else {
// 计算居中位置
const centerOffset = totalOffset - (this.containerHeight / 2) + (this.itemHeights[clickIndex] / 2);
this.scroller.scrollTo({
xOffset: 0,
yOffset: centerOffset,
animation: { duration: 300, curve: Curve.EaseOut } // 平滑动画
});
}
}
}
更多关于HarmonyOS鸿蒙Next中scroll选中滚动居中的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html