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

    向右滑动

相关推荐
一点七加一2 小时前
Harmony鸿蒙开发0基础入门到精通Day13--ArkScript篇
华为·harmonyos
程序员老刘3 小时前
Flutter官方拒绝适配鸿蒙的真相:不是技术问题,而是...
flutter·harmonyos·客户端
平平不平凡4 小时前
鸿蒙组件分级指南:从细胞到思维的系统化角色解析
harmonyos
m0_685535085 小时前
手机镜头设计
华为·光学·光学设计·光学工程·镜头设计
爱笑的眼睛116 小时前
HarmonyOS Marquee组件深度解析:构建高性能滚动视觉效果
华为·harmonyos
不爱说话郭德纲6 小时前
UniappX不会运行到鸿蒙?超超超保姆级鸿蒙开发生成证书以及配置证书步骤
前端·uni-app·harmonyos
m0_685535086 小时前
大疆无人机镜头
华为·光学·光学设计·光学工程·镜头设计
m0_685535086 小时前
无人机镜头设计实例
华为·光学·光学设计·光学工程·镜头设计
爱笑的眼睛118 小时前
HarmonyOS中的智能路线规划与导航应用开发:利用分布式架构构建跨设备体验
华为·harmonyos
爱笑的眼睛1120 小时前
HarmonyOS 应用开发:深入探索截屏与录屏API的创新实践
华为·harmonyos