Assume a class that is derived from UIView
as follows:
class MyView: UIView {
var myImageView: UIImageView
init(frame: CGRect) {
super.init(frame: frame)
}
init(coder aDecoder: NSCoder!) {
super.init(coder: aDecoder)
}
...
If I wanted to have the same code in both of the initializers, like
self.myImageView = UIImageView(frame: CGRectZero)
self.myImageView.contentMode = UIViewContentMode.ScaleAspectFill
and NOT duplicate that code twice in the class implementation, how would I structure the init
methods?
Tried approaches:
- Created a method
func commonInit()
that is called after super.init
-> Swift compiler gives an error about an uninitialized variable myImageView
before calling super.init
- Calling
func commonInit()
before super.init
fails self-evidently with a compiler error "'self' used before super.init call"
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…