Skip to content

Instantly share code, notes, and snippets.

@Exey
Created November 23, 2020 19:11
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 Exey/11411d5eacba329b9563c327fb420a5f to your computer and use it in GitHub Desktop.
Save Exey/11411d5eacba329b9563c327fb420a5f to your computer and use it in GitHub Desktop.
Blueprint+OpenCombine.swift
import UIKit
import OpenCombine
import BlueprintUI
import BlueprintUICommonControls
typealias Published = OpenCombine.Published
final class CounterViewModel {
@Published var totalCount = 0
func increase() {
totalCount += 1
}
func decrease() {
totalCount -= 1
}
}
class ViewController: UIViewController {
// Blueprint
let blueprintView = BlueprintView()
let viewModel = CounterViewModel()
lazy var counterView = BlueprintCounterView(viewModel: viewModel)
var bag = Set<AnyCancellable>()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemGreen
addBlueprintView()
}
func addBlueprintView() {
self.view = blueprintView
viewModel.$totalCount.sink { val in
print("\(val)")
self.updateBlueprintUI()
}.store(in: &bag)
}
func updateBlueprintUI() {
blueprintView.element = counterView.element
}
}
struct BlueprintCounterView {
var viewModel: CounterViewModel
var element: Element {
Column { col in
col.horizontalAlignment = .center
col.add(child: Spacer())
col.add(child: counterColumn)
col.add(child: Spacer())
}
}
var counterColumn: Element {
Column { col in
let label = Label(text: "\(viewModel.totalCount)") {
$0.color = .black
$0.font = .systemFont(ofSize: 32)
}
col.add(child: label)
col.add(child: buttonsRow)
}
.constrainedTo(width: .absolute(200), height: .absolute(100))
}
var buttonsRow: Element {
Row { row in
let buttonDec = Button(onTap: {viewModel.decrease()}, wrapping:
Label(text: " - "){
$0.font = .systemFont(ofSize: 28)
}
).box(background: .lightGray, borders: .solid(color: .black, width: 1))
let buttonInc = Button(onTap: {viewModel.increase()}, wrapping:
Label(text: " + "){
$0.font = .systemFont(ofSize: 28)
}
).box(background: .lightGray, borders: .solid(color: .black, width: 1))
row.add(child: buttonDec)
row.add(child: Spacer().constrainedTo(width: .absolute(20)))
row.add(child: buttonInc)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment