You did not create an initialiser for the your Draw2D class. It needs this to be able to call super.init, this in turn actually creates the UIView stuff from which you are subclassing.
You also created another instance of Draw2D in your class. This is bad, if you actually do this in an initialiser (where that code belongs) it will create an infinite amount of subviews.
Recursive functions are super awesome, recursive initialiser are very bad ;)
import UIKit
class Draw2D: UIView {
// this will create an infinite amount of coloredSquare's => it is a recursive initialiser
let coloredSquare : Draw2D
override init(frame: CGRect) {
coloredSquare = Draw2D(frame: frame)
super.init(frame: frame)
self.frame = frame
coloredSquare.backgroundColor = UIColor.blueColor()
coloredSquare.frame = CGRect(x: 0, y: 120, width: 50, height: 50)
addSubview(coloredSquare)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
After calling super.init() you can call stuff from the super class. Use self for extra clarity, but this is not needed.
class Draw2DCorrected: UIView {
init() {
let rect = CGRect(x: 0, y: 120, width: 50, height: 50)
super.init(frame: rect)
self.frame = rect // inherited stuff from super class -> UIView
self.backgroundColor = UIColor.blueColor() // inherited stuff from super class -> UIView
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
var coloredSquare = Draw2DCorrected() // playground only