I am trying to build a custom UIView and am lost as far as initialization goes.
Code One
class CustomUIView: UIView {
var propertyToInitialize: CGRect
//Custom Initializer
override init(frame: CGRect) {
self.propertyToInitialize = CGRect(x: 0, y: 0, width: (superview?.frame.size.width)!, height: (superview?.frame.size.height)!)
super.init(frame: frame)
}
}
When I use the above code the error XCode gives me is as follows.
Error
Use of 'self' property access 'superview' before super.init initializes self
So I modified my code
Code Two
class CustomUIView: UIView {
var propertyToInitialize: CGRect
//Custom Initializer
override init(frame: CGRect) {
self.propertyToInitialize = CGRect()
super.init(frame: frame)
self.propertyToInitialize = CGRect(x: 0, y: 0, width: (superview?.frame.size.width)!, height: (superview?.frame.size.height)!)
}
}
Question
Is this bad design? Should I take a different approach? Am I initializing the property twice therefore, using more memory?
The whole thing is bad design. Make the propertyToInitialize
an Optional wrapping a CGRect, so that it doesn't need a value at initialization time, and move your code to your view's didMoveToSuperview
, which is the first moment where the concept of a superview has any meaning. Even better, don't make this a property at all; the superview can be examined at anytime you need this information, so it's pointless to duplicate it in a property.