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

    向右滑动

相关推荐
金启攻14 分钟前
【鸿蒙原生应用开发实战】第一篇:项目搭建与首页开发 — 从零构建“宇宙探索“App
harmonyos
非凡大爹19 分钟前
实验十三 华为三层交换机实现 VLAN 间通信实验指导书
网络·计算机网络·华为
坚果派·白晓明1 小时前
鸿蒙 PC应用集成 hwloc:3 大 NAPI & 编译坑详解
c语言·华为·ai编程·harmonyos·atomcode
不羁的木木1 小时前
HarmonyOS AI开发提效工具:DevEco Code & DevEco CLI - AOT编译加速AI应用启动
harmonyos·鸿蒙
木咺吟2 小时前
鸿蒙原生应用实战(三):塔罗牌App开发 — 牌阵解读与交互设计
harmonyos
不喝水就会渴2 小时前
HarmonyOS惰性加载性能优化技术详解(喵屿项目案例)
华为·性能优化·harmonyos
轻口味2 小时前
轻规划鸿蒙开发实战9:对接 Agent Framework Kit,用小艺智能体实现愿景项目体检与自动可行性打分
华为·harmonyos
祭曦念3 小时前
【共创季稿事节】鸿蒙原生 ArkTS 布局精讲:foregroundColor 前景色统一着色
华为·harmonyos
金启攻3 小时前
【鸿蒙原生应用开发实战】第四篇:详情页与收藏交互 — 动态数据切换与用户交互设计
harmonyos
TrisighT3 小时前
Electron 跑在鸿蒙 PC 上比 Windows 还省内存?我测完沉默了
electron·harmonyos