【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: ... })

    向右滑动

相关推荐
梦想不只是梦与想13 分钟前
鸿蒙应用api的兼容性:参数配置(二)
harmonyos·sdk版本·sdkversion
北墨NoLimit5 小时前
鸿蒙线程间通信怎么选:TaskPool、TaskGroup、LongTask 与 Worker 实战
typescript·harmonyos
woshihuanglaoshi7 小时前
错题四科入库:鸿蒙错题本种子数据与复习队列效果
学习·华为·harmonyos·鸿蒙
kiros_wang8 小时前
鸿蒙ArkTS枚举实战|静态枚举、动态枚举业务选型、规范落地与避坑全解
harmonyos
2501_9197490310 小时前
华为鸿蒙免费音乐APP—小羊免费音乐
华为·harmonyos·鸿蒙
世人万千丶10 小时前
物品借还闭环:鸿蒙物品清单种子数据与清单效果
学习·华为·harmonyos·鸿蒙
贾伟康10 小时前
【知律|10】HarmonyOS ArkTS 案例边界实战:明确普法内容不替代法律意见
harmonyos·arkts·arkui·应用合规·内容治理
xq952711 小时前
鸿蒙组件化设计横空出世
harmonyos
特立独行的猫A11 小时前
Tauri v2 桌面应用m3u8dl-tauri移植到 HarmonyOS(鸿蒙 PC)完整实战指南
harmonyos