SwiftUI Atom Properties 使用教程

SwiftUI Atom Properties 使用教程

swiftui-atom-properties⚛️ Atomic approach state management and dependency injection for SwiftUI项目地址:https://gitcode.com/gh_mirrors/sw/swiftui-atom-properties

项目介绍

SwiftUI Atom Properties 是一个专为 SwiftUI 设计的状态管理和依赖注入库。它的灵感来源于 Jotai,一个流行的 React 框架。该库的目标是通过形成小型模块化单元,简化状态管理,使其可以在整个应用程序中组合使用,作为单一数据源,从而更容易地使用仅在状态管理方面必要的内容,而不必担心面向对象编程的复杂性。

项目快速启动

安装

首先,通过 Xcode 菜单添加 Swift Package:

  1. 打开 Xcode,选择 File > Swift Packages > Add Package Dependency...
  2. 输入仓库地址:https://github.com/ra1028/swiftui-atom-properties
  3. 选择版本或分支,然后点击 Next 完成安装。

在你的 Package.swift 文件中添加依赖:

dependencies: [
    .package(url: "https://github.com/ra1028/swiftui-atom-properties", from: "1.0.0")
]

然后在你的目标中包含 Atoms

targets: [
    .target(
        name: "YourTarget",
        dependencies: [
            .product(name: "Atoms", package: "swiftui-atom-properties")
        ]
    )
]

基本使用

在 SwiftUI 应用程序中,确保在 WindowGroup 下放置 AtomRoot

@main
struct TodoApp: App {
    var body: some Scene {
        WindowGroup {
            AtomRoot {
                TodoList()
            }
        }
    }
}

创建一个简单的 Todo 应用示例:

struct TodoList: View {
    @ViewContext var context

    var body: some View {
        List {
            ForEach(context.read(TodoAtomFamily())) { todo in
                Text(todo.title)
            }
        }
    }
}

应用案例和最佳实践

动态初始化 Atom 家族

每个 Atom 必须有一个唯一的键来与其值唯一关联。可以通过显式指定键来传递任意外部参数到 Atom:

struct FetchUserAtom: ThrowingTaskAtom {
    let id: Int
    var key: Int { id }
}

使用 read(_:) 函数

read(_:) 函数是一种在不监听和接收未来更新的情况下获取 Atom 数据的方法:

struct TextCopyView: View {
    @ViewContext var context

    var body: some View {
        Button("Copy") {
            UIPasteboard.general.string = context.read(TextAtom())
        }
    }
}

典型生态项目

SwiftUI Atom Properties 可以与其他 SwiftUI 生态系统项目结合使用,例如 Combine、Core Data 等,以实现更复杂的状态管理和数据持久化。通过结合这些工具,可以构建出高性能、可维护的应用程序。

swiftui-atom-properties⚛️ Atomic approach state management and dependency injection for SwiftUI项目地址:https://gitcode.com/gh_mirrors/sw/swiftui-atom-properties

  • 7
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

娄妃元Kacey

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值