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

    向右滑动

相关推荐
wszy18091 小时前
新文章标签:让用户一眼发现最新内容
java·python·harmonyos
wszy18091 小时前
顶部标题栏的设计与实现:让用户知道自己在哪
java·python·react native·harmonyos
Van_Moonlight1 小时前
RN for OpenHarmony 实战 TodoList 项目:空状态占位图
javascript·开源·harmonyos
anyup3 小时前
2026第一站:分享我在高德大赛现场学到的技术、产品与心得
前端·架构·harmonyos
anyup3 小时前
从赛场到产品:分享我在高德大赛现场学到的技术、产品与心得
前端·harmonyos·产品
Van_Moonlight5 小时前
RN for OpenHarmony 实战 TodoList 项目:顶部导航栏
javascript·开源·harmonyos
Swift社区5 小时前
H5 与 ArkTS 通信的完整设计模型
uni-app·harmonyos
程序猿追6 小时前
【鸿蒙PC桌面端实战】从零构建 ArkTS 高性能图像展示器:DevEco Studio 调试与 HDC 命令行验证全流程
华为·harmonyos
前端世界7 小时前
设备找不到、Ability 启不动?一次讲清 DevEco Studio 调试鸿蒙分布式应用
华为·harmonyos
行者968 小时前
OpenHarmony上Flutter粒子效果组件的深度适配与实践
flutter·交互·harmonyos·鸿蒙