iOS 14 @AppStorage
属性包装器的即插即用替代品。
@AppStorage
属性包装器 100% 相同的 APIUserDefaults
更改时自动更新// iOS 14
@AppStorage("text") var text = "Default Text"
@AppStorage("magic_number", store: .customUserDefaults) var magicNumber = 42
// iOS 13
@AppStorageCompat("text") var text = "Default Text"
@AppStorageCompat("magic_number", store: .customUserDefaults) var magicNumber = 42
import SwiftUI
import AppStorage
enum StringEnum: String, Identifiable {
case a, b, c
var id: String { rawValue }
}
enum IntEnum: Int, Identifiable {
case this, that, theOther
var id: Int { rawValue }
}
struct ContentView: View {
@AppStorageCompat("text", store: .standard) var text = "Default Text"
@AppStorageCompat("string_enum") var selectionString: StringEnum = .a
@AppStorageCompat("int_enum") var selectionInt: IntEnum = .this
var body: some View {
List {
Section(header: Text("Acts like a persistent @State")) {
TextField("Change me", text: $text)
TextField("Change me, too!", text: $text)
}
Section(header: Text("Change UserDefaults without property wrapper")) {
Button("Sneakily change a UserDefault") {
UserDefaults.standard.setValue("One more thing...", forKey: "text")
}
Button("Remove a UserDefault") {
UserDefaults.standard.setValue(nil, forKey: "text")
}
}
Section(header: Text("Enums with raw values")) {
Picker("Pick Me", selection: $selectionString) {
Text("a").tag(StringEnum.a)
Text("b").tag(StringEnum.b)
Text("c").tag(StringEnum.c)
}.pickerStyle(SegmentedPickerStyle())
Picker("Pick Me", selection: $selectionInt) {
Text("this").tag(IntEnum.this)
Text("that").tag(IntEnum.that)
Text("the other").tag(IntEnum.theOther)
}.pickerStyle(SegmentedPickerStyle())
}
}.listStyle(GroupedListStyle())
}
}
将软件包添加到您的 Package.swift 文件
dependencies: [
.package(url: "https://github.com/xavierLowmiller/AppStorage.git", .upToNextMajor(from: "1.0.4"))
]
将 pod 添加到您的 Podfile
platform :ios, '13.0'
use_frameworks!
target 'MyApp' do
pod 'AppStorage', '~> 1.0.4'
end
将此行添加到您的 Cartfile
github "xavierLowmiller/AppStorage" ~> 1.0.4
因为它只是一个单独的文件,所以您可以直接下载并将其拖到您的项目中。