Skip to content

Instantly share code, notes, and snippets.

@fatbobman
Created May 25, 2025 12:45
Show Gist options
  • Save fatbobman/5ab86c35ac8cee93c8ac6ac4228a28a9 to your computer and use it in GitHub Desktop.
Save fatbobman/5ab86c35ac8cee93c8ac6ac4228a28a9 to your computer and use it in GitHub Desktop.
ObservableCloud Macro Demo Code
import ObservableDefaults
import SwiftUI
@ObservableCloud
class CloudSetting {
var number = 1
var color: Colors = .red
var style: FontStyle = .style1
}
struct ContentView: View {
@State var setting = CloudSetting()
var body: some View {
Form {
LabeledContent {
Stepper(value: $setting.number, in: 0 ... 10) {
Text(setting.number, format: .number)
}
} label: {
Text("Number")
.contentTransition(.numericText())
}
.foregroundStyle(setting.color.color)
.font(.system(size: setting.style.size, weight: setting.style.weight.weight))
LabeledContent {
Menu(setting.color.name) {
Picker("Color", selection: $setting.color) {
ForEach(Colors.allCases, id: \.self) { color in
Image(systemName: "circle")
.tint(color.color)
.tag(color)
}
}
.pickerStyle(.segmented)
.paletteSelectionEffect(.symbolVariant(.fill))
}
.bold()
} label: {
Text("Color")
}
Picker("Font Style", selection: $setting.style) {
ForEach(
[FontStyle.style1, FontStyle.style2, FontStyle.style3],
id: \.self)
{ style in
Text("style\(style.id)").textCase(.uppercase)
.tag(style)
}
}
if ProcessInfo.processInfo.environment["XCODE_RUNNING_FOR_PREVIEWS"] == "1" {
Text("This is a preview mode. The settings will not be synced.")
} else {
Text(
"You need to enable CloudKit Key-Value Storage in your project to sync settings.")
}
}
}
}
struct FontStyle: CodableCloudPropertyListValue, Hashable, Identifiable {
let size: CGFloat
let weight: Weight
let id: Int
static let style1 = FontStyle(size: 20, weight: .bold, id: 1)
static let style2 = FontStyle(size: 30, weight: .regular, id: 2)
static let style3 = FontStyle(size: 40, weight: .heavy, id: 3)
enum Weight: Int, Codable {
case bold, regular, heavy
var weight: SwiftUI.Font.Weight {
switch self {
case .bold: return .bold
case .regular: return .regular
case .heavy: return .heavy
}
}
}
}
enum Colors: Int, CaseIterable, Hashable, Identifiable {
case red, yellow, blue, green, orange, purple
var color: Color {
switch self {
case .red: return .red
case .yellow: return .yellow
case .blue: return .blue
case .green: return .green
case .orange: return .orange
case .purple: return .purple
}
}
var id: Self { self }
var name: String {
switch self {
case .red: return "Red"
case .yellow: return "Yellow"
case .blue: return "Blue"
case .green: return "Green"
case .orange: return "Orange"
case .purple: return "Purple"
}
}
}
#Preview {
ContentView()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment