Skip to content

Instantly share code, notes, and snippets.

@aciidgh
Created January 21, 2016 09:00
Show Gist options
  • Save aciidgh/43fde24aac0b42d63af6 to your computer and use it in GitHub Desktop.
Save aciidgh/43fde24aac0b42d63af6 to your computer and use it in GitHub Desktop.
protocol TagView {
var view: UIView { get }
}
protocol ViewConvertible {
func getView() -> UIView
}
struct ViewModel<T: ViewConvertible>: TagView {
let data: T
let view: UIView
init(data: T) {
self.data = data
self.view = data.getView()
}
}
extension Bool: ViewConvertible {
func getView() -> UIView {
let view = UIView(frame: CGRectMake(0, 0, 100, 100))
view.backgroundColor = self ? UIColor.redColor() : UIColor.blueColor()
return view
}
}
extension String: ViewConvertible {
func getView() -> UIView {
let view = UIView(frame: CGRectMake(0, 0, 100, 100))
view.backgroundColor = UIColor.blackColor()
return view
}
}
class ViewContainer: UIView {
var tagViews = [TagView]()
func add(tagView: TagView) {
let view = tagView.view
if let lastView = tagViews.last {
view.frame.origin.x = lastView.view.frame.origin.x + lastView.view.frame.size.width
}
tagViews.append(tagView)
addSubview(view)
}
}
let container = ViewContainer(frame: CGRectMake(0, 0, 400, 100))
container.add(ViewModel(data: true))
container.add(ViewModel(data: "Hello"))
container.add(ViewModel(data: false))
container.add(ViewModel(data: true))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment