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

    向右滑动

相关推荐
kirk_wang2 分钟前
将 Flutter 条码扫描插件 `flutter_barcode_scanner` 适配到鸿蒙平台:一次深度实践
flutter·移动开发·跨平台·arkts·鸿蒙
liuhaikang1 小时前
鸿蒙炫酷的动画库——ohos-vap
华为·harmonyos
特立独行的猫a1 小时前
鸿蒙PC命令行适配】移植x264库到鸿蒙PC的完整教程(使用官方最新lycium_plusplus框架)
华为·harmonyos·三方库移植·鸿蒙pc
Hello_MyDream3 小时前
鸿蒙getContext(this)弃用后的替代方法
华为·harmonyos
航Hang*4 小时前
第五章:网络系统建设与运维(高级)—— VLAN高级特性
运维·服务器·网络·笔记·计算机网络·华为·ensp
kirk_wang4 小时前
Flutter三方库鸿蒙适配实战:让flutter_sms在HarmonyOS上跑起来
flutter·移动开发·跨平台·arkts·鸿蒙
再坚持一下!!!5 小时前
数通——华为HCIA
华为
前端世界5 小时前
鸿蒙在教育场景的落地实践:智慧课堂的分布式设计思路
分布式·华为·harmonyos
Lancker6 小时前
拥抱纯血鸿蒙经验分享 实战鸿蒙2025激励计划上架8个鸿蒙APP
华为·harmonyos
申耀的科技观察7 小时前
【观察】华为坤灵:茶间一隅见智能,化繁为简助鹏城
华为