Skip to content

Instantly share code, notes, and snippets.

@chkpnt
Created July 17, 2020 16:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chkpnt/d4143692370adfa215c21290f0af8179 to your computer and use it in GitHub Desktop.
Save chkpnt/d4143692370adfa215c21290f0af8179 to your computer and use it in GitHub Desktop.
Persisting Color in SwiftUI
//
// PlaygroundView.swift
// PlaygroundApp
//
// Created by Gregor Dschung on 17.07.20.
//
import SwiftUI
struct PlaygroundView: View {
@ObservedObject var viewModel: PlaygroundViewModel
var body: some View {
VStack {
Text("Hello!")
ColorPicker("Set background color", selection: $viewModel.color)
}.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(viewModel.color)
.onAppear() {
self.viewModel.load()
}
}
}
class PlaygroundViewModel: ObservableObject {
@Published var color: Color = Color.white {
didSet {
interactor.save(color: color.rgba())
}
}
private let interactor: PlaygroundInteractor
init(interactor: PlaygroundInteractor) {
self.interactor = interactor
}
func load() {
let previousColor = interactor.loadColor()
color = Color(previousColor)
}
}
// I do not think an "Interactor" should interact with UIKit or SwiftUI classes, therefore the "CoreColor".
// But of course this is a matter of taste...
class PlaygroundInteractor {
private var color: CoreColor = (0.5, 0.5, 0.8, 1)
func loadColor() -> CoreColor {
// load from storage ...
return color
}
func save(color: CoreColor) {
print("Color to save: \(color)")
self.color = color
}
}
typealias CoreColor = (red: Double, green: Double, blue: Double, opacity: Double)
extension Color {
init(_ rgba: CoreColor) {
self.init(.sRGB, red: rgba.red, green: rgba.green, blue: rgba.blue, opacity: rgba.opacity)
}
func rgba() -> CoreColor {
let uicolor = UIColor(self)
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
uicolor.getRed(&r, green: &g, blue: &b, alpha: &a)
return (red: Double(r), green: Double(r), blue: Double(b), opacity: Double(a))
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
let interactor = PlaygroundInteractor()
let viewModel = PlaygroundViewModel(interactor: interactor)
PlaygroundView(viewModel: viewModel)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment