SwipeView.ets 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. @Component
  2. export struct SwipeView {
  3. private _scroller: Scroller = new Scroller()
  4. @State h: Length = 40
  5. @State downX: number = 0
  6. @Builder
  7. doNothingBuilder() {
  8. }
  9. @BuilderParam customBuilderParam: () => void = this.doNothingBuilder
  10. // @BuilderParam btnBuilder: () => void = this.doNothingBuilder
  11. build() {
  12. Scroll(this._scroller) {
  13. Row() {
  14. this.customBuilderParam()
  15. Text('删除')
  16. .backgroundColor('red')
  17. .width(70)
  18. .fontColor('white')
  19. .height(this.h)
  20. .textAlign(TextAlign.Center)
  21. .fontSize(16)
  22. // if (this.btnBuilder === this.doNothingBuilder) {
  23. // Text('删除')
  24. // }
  25. // if (this.btnBuilder !== this.doNothingBuilder) {
  26. // this.btnBuilder()
  27. // }
  28. }.onSizeChange((oldValue: SizeOptions, newValue: SizeOptions) => {
  29. this.h = newValue.height ?? 40
  30. }).alignItems(VerticalAlign.Center)
  31. }.width('100%').scrollable(ScrollDirection.Horizontal).scrollBar(BarState.Off)
  32. .onTouch((event: TouchEvent) => { // 触摸事件
  33. // 判断是否有打开删除组件,有则关闭
  34. // 根据触摸类型判断
  35. switch (event.type) {
  36. case TouchType.Down: // 触摸按下
  37. // 记录按下的x轴坐标
  38. this.downX = event.touches[0].x
  39. break
  40. case TouchType.Up: // 触摸抬起
  41. // 触摸抬起,根据x轴总偏移量,判断是否打开删除
  42. let xOffset = event.touches[0].x - this.downX
  43. // 防止消费点击事件
  44. if (xOffset == 0) {
  45. return
  46. }
  47. // 滑到x轴的位置
  48. let toxOffset = 0
  49. // 开启删除的对象置为null
  50. // 偏移量超过删除按钮一半且左滑,设置打开
  51. if (Math.abs(xOffset) > 35 && xOffset < 0) {
  52. // 删除布局宽度
  53. toxOffset = 70
  54. }
  55. // 滑动指定位置,设置动画
  56. this._scroller.scrollTo({ xOffset: toxOffset, yOffset: 0,
  57. animation: { duration: 300, curve: Curve.Linear } })
  58. // 重置按下的x轴坐标
  59. this.downX = 0
  60. break
  61. }
  62. })
  63. }
  64. }