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

    向右滑动

相关推荐
想你依然心痛28 分钟前
HarmonyOS 6(API 23)智能体驱动的沉浸式AR城市地下管网运维中心
运维·ar·harmonyos·智能体
非凡大爹1 小时前
实验十 华为路由器和交换机实现RIP 动态路由协议配置实验指导书
运维·网络·计算机网络·华为
Goway_Hui1 小时前
【鸿蒙原生应用开发--ArkUI--014】Expense-tracker 记账应用开发教程
华为·harmonyos
不羁的木木1 小时前
《HarmonyOS技术精讲》五:实战项目 ── 智能支架助手
华为·harmonyos
枫叶丹42 小时前
【HarmonyOS 6.0】Map Kit瓦片图层深度解析:本地加载方式与瓦片数据缓存能力
开发语言·缓存·华为·harmonyos
大雷神2 小时前
第29篇|单拍按钮背后:从点击到 PhotoOutput 回调
harmonyos
不羁的木木2 小时前
《HarmonyOS底部页签-沉浸光感组件实战》模糊样式:打造毛玻璃效果
华为·harmonyos
大雷神8 小时前
第26篇|单摄预览会话:CameraInput、PreviewOutput、PhotoSession 的关系
harmonyos
博客-小覃14 小时前
Zabbix之华为交换机的日志记录信息操作详细教程
服务器·网络·华为·zabbix
不羁的木木17 小时前
Form Kit(卡片开发服务)学习笔记01-核心概念与架构设计
笔记·学习·harmonyos