【HarmonyOS】ArkUI - 向左/向右滑动删除

核心知识点:List容器 -> ListItem -> swipeAction

先看效果图:

代码实现:

ts 复制代码
// 任务类
class Task {
  static id: number = 1
  // 任务名称
  name: string = `任务${Task.id++}`
  // 任务状态
  finished: boolean = false
}
ts 复制代码
// 统一的卡片样式
@Styles function card() {
  .width('95%')
  .padding(20)
  .backgroundColor(Color.White)
  .borderRadius(15)
  .shadow({ radius: 6, color: '#1F000000', offsetX: 2, offsetY: 4 })
}
ts 复制代码
@Entry
@Component
struct PropPage {
  // 总任务数量
  @State totalTask: number = 0
  // 已完成任务数量
  @State finishTask: number = 0
  // 任务数组
  @State tasks: Task[] = []

  build() {
    Column({ space: 10 }) {
      // 新增任务按钮
      Button('新增任务')
        .width(200)
        .margin({ top: 10 })
        .onClick(() => {
          // 新增任务数据
          this.tasks.push(new Task())
          // 更新任务总数量
          this.totalTask = this.tasks.length
        })

      // 任务列表
      List({ space: 10 }) {
        ForEach(
          this.tasks,
          (item: Task, index) => {
            ListItem() {
              Row() {
                Text(item.name)
                  .fontSize(20)
                Checkbox()
                  .select(item.finished)
                  .onChange(val => {
                    // 更新当前任务状态
                    item.finished = val
                    // 更新已完成任务数量
                    this.finishTask = this.tasks.filter(item => item.finished).length
                  })
              }
              .card()
              .justifyContent(FlexAlign.SpaceBetween)
            }
            .swipeAction({ end: this.DeleteButton(index) })
          }
        )
      }
      .width('100%')
      .layoutWeight(1)
      .alignListItem(ListItemAlign.Center)
    }
    .width('100%')
    .height('100%')
    .backgroundColor('#F1F2F3')
  }

  @Builder DeleteButton(index: number) {
    Button() {
      Image($r('app.media.delete'))
        .fillColor(Color.White)
        .width(20)
    }
    .width(40)
    .height(40)
    .type(ButtonType.Circle)
    .backgroundColor(Color.Red)
    .margin(5)
    .onClick(() => {
      this.tasks.splice(index, 1)
      this.totalTask = this.tasks.length
      this.finishTask = this.tasks.filter(item => item.finished).length
    })
  }
}
  • .swipeAction({ end: ... })

    向左滑动

  • .swipeAction({ start: ... })

    向右滑动

相关推荐
生如夏花℡1 小时前
HarmonyOS学习记录4
学习·华为·harmonyos
九章云极AladdinEdu1 小时前
华为昇腾NPU与NVIDIA CUDA生态兼容层开发实录:手写算子自动转换工具链(AST级代码迁移方案)
人工智能·深度学习·opencv·机器学习·华为·数据挖掘·gpu算力
xq95271 小时前
编程之路2025年中总结,勇往直前 再战江湖
harmonyos
枫叶丹42 小时前
【HarmonyOS Next之旅】DevEco Studio使用指南(四十二) -> 动态修改编译配置
华为·harmonyos·deveco studio·harmonyos next
众乐 认证3 小时前
HUAWEI HiCar6.0的新变化
华为·hicar
前端世界14 小时前
鸿蒙UI开发全解:JS与Java双引擎实战指南
javascript·ui·harmonyos
阿巴~阿巴~16 小时前
操作系统核心技术剖析:从Android驱动模型到鸿蒙微内核的国产化实践
android·华为·harmonyos
iMerryou17 小时前
鸿蒙的动态渐变背景实现
harmonyos
Keya20 小时前
在HarmonyOS(鸿蒙)中H5页面中的视频不会自动播放
app·harmonyos·arkts
二二孚日20 小时前
自用华为ICT云赛道AI第一章知识点-机器学习的常见算法
人工智能·华为