你没有创建为一个初始化器你的Draw2D类。它需要这个能够调用super.init,这反过来实际上创建了你从中继承的UIView的东西。
您还在班级中创建了另一个Draw2D实例。这很糟糕,如果你真的在初始化程序中执行此操作(代码属于此代码),它将创建无限量的子视图。
递归函数是超级真棒,递归的初始化器是非常糟糕;)
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")
}
}
调用super.init(),您可以从超一流的呼叫东西之后。使用自我来增加清晰度,但这不是必需的。
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
这些天,使用容器视图http://stackoverflow.com/a/23403979/294884 – Fattie