Swift 初始化 - 为什么要调用多个初始化函数?
Swift Initialization - Why are multiple init functions being called?
这是我的 class 与覆盖初始化
class BottomView: UIView {
// MARK: - initilization
override init() {
println("init")
super.init()
setup()
}
override init(frame: CGRect) {
println("init frame")
super.init(frame: frame)
setup()
}
required init(coder aDecoder: NSCoder) {
println("init decoder")
super.init(coder: aDecoder)
setup()
}
func setup() {
println("setup")
}
}
然后我在 ViewController 中使用以下代码初始化
class ViewController: UIViewController {
let bottomView = BottomView()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
bottomView.frame = CGRectMake(0.0, self.view.frame.height/2.0, self.view.frame.width, self.view.frame.height/2.0)
bottomView.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleTopMargin
self.view.addSubview(bottomView)
}
}
我的输出是
init
init frame
setup
setup
所以我的问题是,为什么要调用 init(frame:)?
super.init()
呼叫 self.init(frame:...)
。本质上,这只是他们说 frame
是可选的方式;如果你不通过,他们会分配一个 (0,0,0,0)
.
的框架
func init() {
self.init(frame:CGRectMake(0,0,0,0));
}
这是我的 class 与覆盖初始化
class BottomView: UIView {
// MARK: - initilization
override init() {
println("init")
super.init()
setup()
}
override init(frame: CGRect) {
println("init frame")
super.init(frame: frame)
setup()
}
required init(coder aDecoder: NSCoder) {
println("init decoder")
super.init(coder: aDecoder)
setup()
}
func setup() {
println("setup")
}
}
然后我在 ViewController 中使用以下代码初始化
class ViewController: UIViewController {
let bottomView = BottomView()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
bottomView.frame = CGRectMake(0.0, self.view.frame.height/2.0, self.view.frame.width, self.view.frame.height/2.0)
bottomView.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleTopMargin
self.view.addSubview(bottomView)
}
}
我的输出是
init
init frame
setup
setup
所以我的问题是,为什么要调用 init(frame:)?
super.init()
呼叫 self.init(frame:...)
。本质上,这只是他们说 frame
是可选的方式;如果你不通过,他们会分配一个 (0,0,0,0)
.
func init() {
self.init(frame:CGRectMake(0,0,0,0));
}