Skip to content

Instantly share code, notes, and snippets.

@Exey
Created November 23, 2020 17:56
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/085f7d086d8066afe3fab661355bc87d to your computer and use it in GitHub Desktop.
Save Exey/085f7d086d8066afe3fab661355bc87d to your computer and use it in GitHub Desktop.
Render+OpenCombine.swift
import UIKit
import CoreRender
import Render
import OpenCombine
final class ViewController: UIViewController {
var hostingView: HostingView!
let contex = Context()
var coreRenderView: CounterView?
override func viewDidLoad() {
hostingView = HostingView(context: contex, with: [.useSafeAreaInsets]) { context in
Component<CounterViewModel>(context: context) { context, viewModel in
let view = CounterView(context: context, viewModel: viewModel)
self.coreRenderView = view
return view.body
}.builder()
}
self.view = hostingView
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
hostingView.setNeedsLayout()
}
}
typealias Published = OpenCombine.Published
final class CounterViewModel: Coordinator {
@Published var totalCount = 0
func increase() {
totalCount += 1
setNeedsReconcile()
}
func decrease() {
totalCount -= 1
setNeedsReconcile()
}
override func onTouchUp(inside sender: UIView) {
if let button = sender as? UIButton, button.titleLabel?.text == "+" {
increase()
} else {
decrease()
}
}
}
// View
struct CounterView {
var context: Context
var viewModel: CounterViewModel
var body: OpaqueNodeBuilder {
VStackNode {
LabelNode(text: "\(viewModel.totalCount)")
.font(.systemFont(ofSize: 30, weight: .black))
.textAlignment(.center)
.background(.secondarySystemBackground)
.width(150)
.height(64)
.margin(10)
.cornerRadius(8)
HStackNode {
ButtonNode(reuseIdentifier: "btn_decrease", target: viewModel)
.text("-")
.font(UIFont.systemFont(ofSize: 24, weight: .black))
.background(.systemTeal)
.padding(6)
.cornerRadius(8)
.margin(20)
ButtonNode(reuseIdentifier: "btn_increase", target: viewModel)
.text("+")
.font(UIFont.systemFont(ofSize: 24, weight: .black))
.background(.systemTeal)
.padding(6)
.cornerRadius(8)
.margin(20)
}
}
.alignItems(.center)
.matchHostingViewWidth(withMargin: 0)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment