具体实现示例如下:
@Entry
@Component
struct ListSwipe {
@State itemIndexArr: number[] = [0, 1, 2, 3, 4, 5];
// 存储每个列表项的滑动状态(0:未滑动,-110:完全滑出)
@State swipeStatus: number[] = [];
aboutToAppear() {
// 初始化滑动状态数组,与列表项数量一致
this.itemIndexArr.forEach(() => {
this.swipeStatus.push(0);
});
}
// 切换滑动状态的方法
toggleSwipe(index: number) {
// 如果当前未滑动则滑出,已滑出则收起
this.swipeStatus[index] = this.swipeStatus[index] === 0 ? -110 : 0;
}
@Builder
itemEnd(index: number) {
Row() {
Button('按钮')
.width(80)
.onClick(() => {
// 按需添加功能
console.info(`index: ${index}`);
});
}
.width(100)
.height(100)
.justifyContent(FlexAlign.SpaceEvenly);
}
build() {
Column() {
List({ space: 3 }) {
ForEach(this.itemIndexArr, (item: number, index: number) => {
ListItem() {
Stack({ alignContent: Alignment.End }) {
// 滑动操作按钮(始终在底层)
this.itemEnd(index);
// 列表项主内容(可滑动部分)
Row() {
Text('' + item)
.fontSize(16);
}
.width('100%')
.height(100)
.justifyContent(FlexAlign.Center)
.borderRadius(18)
.padding({ left: 16, right: 16 })
.backgroundColor(Color.White)
.onClick(() => {
// 点击图片触发滑动状态切换
this.toggleSwipe(index);
})
// 通过translate实现滑动效果
.translate({ x: this.swipeStatus[index] })
// 添加滑动动画
.animation({
duration: 300,
curve: Curve.EaseOut
})
// 支持手动滑动手势
.gesture(
PanGesture({ direction: PanDirection.Horizontal })
.onActionUpdate((event: GestureEvent) => {
// 限制滑动范围在0到110之间
let newX = (this.swipeStatus[index] + event.offsetX) as number;
if (newX > 0) {
newX = 0;
}
if (newX < -110) {
newX = -110;
}
this.swipeStatus[index] = newX;
})
.onActionEnd(() => {
// 滑动结束后自动调整状态(超过一半则完全展开,否则收起)
if (this.swipeStatus[index] < -65) {
this.swipeStatus[index] = -110;
} else {
this.swipeStatus[index] = 0;
}
})
);
};
}
.padding({ left: 20, right: 20 })
.margin({ top: 16 });
});
}
.edgeEffect(EdgeEffect.None)
.scrollBar(BarState.Off);
}
.backgroundColor(0xDCDCDC)
.expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
.width('100%')
.height('100%');
}
} 实现效果如下图所示:
