Skip to content

Instantly share code, notes, and snippets.

@SocialKitLtd
Created August 10, 2019 16:24
Show Gist options
  • Save SocialKitLtd/a1549db6f3f06389a29033d47a079f1d to your computer and use it in GitHub Desktop.
Save SocialKitLtd/a1549db6f3f06389a29033d47a079f1d to your computer and use it in GitHub Desktop.
import UIKit
protocol CanvasItemProtocol
{
var scale : CGFloat { get set }
}
class CanvasItem : CanvasItemProtocol
{
public var scale : CGFloat = 1.0
}
class StickerItem: CanvasItem
{
public var stickerName : String = ""
}
class ShapeItem: CanvasItem
{
public var color: UIColor = .red
}
class ViewItem<T: CanvasItemProtocol> : UIView
{
let canvasItem: T
init(_ item: T)
{
canvasItem = item
super.init(frame: .zero)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class CanvasShapeView: ViewItem<ShapeItem> { }
class CanvasStickerView: ViewItem<StickerItem> {}
let shapeItem = ShapeItem()
let stickerItem = StickerItem()
let shapeView = ViewItem<ShapeItem>(shapeItem)
let stickerView = ViewItem<StickerItem>(stickerItem)
let superview = UIView()
superview.addSubview(shapeView)
superview.addSubview(stickerView)
for canvasItemView in superview.subviews.compactMap({$0 as? ViewItem<CanvasItem>}) {
print(canvasItemView.canvasItem.scale) // **access only the common properties**
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment