Skip to content

Instantly share code, notes, and snippets.

@werediver
Last active October 19, 2016 16:14
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 werediver/8a1b7e00606db6f524a8cfe245f0696e to your computer and use it in GitHub Desktop.
Save werediver/8a1b7e00606db6f524a8cfe245f0696e to your computer and use it in GitHub Desktop.
A concept of UI styling for iOS
//: Playground - noun: a place where people can play
import UIKit
// MARK: - Skeleton
protocol StyleProtocol {
func apply(to some: Any)
}
struct Style<Marker, Target>: StyleProtocol {
private let body: (Target) -> ()
func apply(to some: Any) {
if let _ = some as? Marker, some = some as? Target {
body(some)
}
}
}
struct StyleSheet: StyleProtocol {
private let styles: [StyleProtocol]
func apply(to some: Any) {
styles.forEach { $0.apply(to: some) }
}
}
// MARK: - Example
// Don't focus on this.
struct Palette {
static let bodyFont = UIFont.systemFontOfSize(UIFont.systemFontSize())
static let captionFont = UIFont.systemFontOfSize(UIFont.smallSystemFontSize())
}
protocol BodyFontStyle {}
protocol CaptionFontStyle {}
protocol MultilineLabelStyle {}
let style = StyleSheet(styles: [
Style<BodyFontStyle, UILabel> {
$0.font = Palette.bodyFont
},
Style<BodyFontStyle, UITextView> {
$0.font = Palette.bodyFont
},
Style<CaptionFontStyle, UILabel> {
$0.font = Palette.captionFont
},
Style<CaptionFontStyle, UITextView> {
$0.font = Palette.captionFont
},
Style<MultilineLabelStyle, UILabel> {
$0.numberOfLines = 0
}
])
final class BodyLabel: UILabel, BodyFontStyle {
override init(frame: CGRect) {
super.init(frame: frame)
style.apply(to: self)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
style.apply(to: self)
}
}
final class CaptionLabel: UILabel, CaptionFontStyle, MultilineLabelStyle {
override init(frame: CGRect) {
super.init(frame: frame)
style.apply(to: self)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
style.apply(to: self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment