-
Notifications
You must be signed in to change notification settings - Fork 0
/
ASDisplayNode+Style.swift
80 lines (63 loc) · 2.39 KB
/
ASDisplayNode+Style.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
//
// ASDisplayNode+Style.swift
// pinknoise
//
// Created by Adam Tait on 2/22/18.
// Copyright © 2018 Sisterical Inc. All rights reserved.
//
import UIKit
import AsyncDisplayKit
func toCgFloat(anyNumber n: Any) -> CGFloat
{
if let c = n as? CGFloat { return c }
else if let d = n as? Double { return CGFloat(d) }
else if let f = n as? Float { return CGFloat(f) }
return CGFloat(n as! Int)
}
extension ASDisplayNode
// IMPORTANT! to begin, you must retrieve self.styleset (this sets up the observer on changes to ASDisplayNode.styleset)
{
private static let association = ObjectAssociation<MutableProperty<Style>>()
// Style
static let defaultStyle : Style = [StyleType.bgColor : UIColor.white,
StyleType.fgColor : UIColor.blue,
StyleType.fontName : UIFont.systemFont(ofSize: 12.0).fontName,
StyleType.fontSize : UIFont.systemFontSize]
static func cascade(styles: [Style]) -> Style {
return ASControlNode.defaultStyle.merge(styles)
}
var styleset: MutableProperty<Style>
// NOTE: can't use 'style' b/c ASLayoutElement (subclass of ASDisplayNode) has already claimed it
{
get {
if let v = ASDisplayNode.association[self] { return v }
// else create+save new
let v = MutableProperty<Style>(ASDisplayNode.defaultStyle)
ASDisplayNode.association[self] = v
_ = v.addObserver(styleChanged)
return v
}
}
// public interface
func apply(style : Style)
{
if let v = style[.bgColor] as? UIColor { self.backgroundColor = v }
if let v = style[.fgColor] as? UIColor { self.tintColor = v }
if let v = style[.borderColor] as? UIColor { self.borderColor = v.cgColor }
if let v = style[.borderWidth] {
self.borderWidth = toCgFloat(anyNumber: v)
}
if let v = style[.cornerRadius] {
self.cornerRadius = toCgFloat(anyNumber: v)
}
if let v = style[.alpha] {
self.alpha = toCgFloat(anyNumber: v)
}
}
// observers
func styleChanged(_: Observable)
{
let s = ASDisplayNode.cascade(styles: [styleset.get()!])
apply(style: s)
}
}