The very straightforward answer, 2024
class TemperatureGraph: UIView {
var data: [Temperature]
required init(data: [Temperature]) {
self.data = data
super.init(frame: .zero)
}
required init?(coder aDecoder: NSCoder) {
self.data = []
super.init(coder: aDecoder)
}
}
another example
class TemperatureGraph: UIView {
var data: YourDataClass
required init(data: YourDataClass) {
self.data = data
super.init(frame: .zero)
}
required init?(coder aDecoder: NSCoder) {
self.data = YourDataClass()
super.init(coder: aDecoder)
}
}
another example
class TemperatureGraph: UIView {
var height: Int
var color: UIColor
required init(height: Int, color: UIColor) {
self.height = height
self.color = color
super.init(frame: .zero)
}
required init?(coder aDecoder: NSCoder) {
self.height = 180
self.color = .blue
super.init(coder: aDecoder)
}
}
The formula is
in required init, set the properties you added, then call super
in the coder init, set the properties you added to whatever defaults you prefer, then call super
That's it.
Note that you don't have to pass in the values, as long as you initialize them (in the two calls) before calling super.
For example
class Countdown: UIView {
var seconds: Int
required init() {
self.seconds = 10
super.init(frame: .zero)
}
required init?(coder aDecoder: NSCoder) {
self.seconds = 10
super.init(coder: aDecoder)
}
}