Reputation: 1218
I've read several posts about why you would need to implement the constructor init(coder:) of a UIView when trying to create your own constructor (it's because UIView inherits from NSCoding protocal and by using a custom contructor it will no longer inherit the parent constructors.
My question is why this class doesn't need to implement init(coder:)
import UIKit
class CardView: UIView {
@IBInspectable var cornerRadius : CGFloat = 3.0
// layoutSubviews is called when view is created
override func layoutSubviews() {
layer.cornerRadius = cornerRadius
layer.masksToBounds = true // Set the false to see shadows. TODO: Figure out how to clip subviews and allow a shadow
layer.shadowOffset = CGSize(width: 0, height: 3)
layer.shadowColor = UIColor.black.cgColor
layer.shadowRadius = 9.0
layer.shadowOpacity = 0.12
}
}
when this class does:
import UIKit
class ColorView: UIView {
var color : UIColor
override func layoutSubviews() {
//layer.backgroundColor = self.color.cgColor
}
}
I'm looking for the technical reason that the ColorView class now requires a constructor when the CardView class doesn't.
Upvotes: 1
Views: 135
Reputation: 760
For the initialization of class in Swift, you have to make sure that at the time of initialization either you have given a default value to all the stored properties or you have declared them as optional.
By declaring as Optional means, it's default value at the time of initialization is nil.
So in the CardView there is only one stored property "cornerRadius" and you have given the default value 3.0. So no init(coder:) required.
In ColorView class, there is only one store property "color", neither you have given a value to it nor you declared it as optional. So init(coder:) is required.
Upvotes: 2
Reputation: 17882
It's because ColorView
does not provide any initializer or default value for color
. If you change the var definition to e.g. var color = UIColor.black
the initializer requirement goes away.
Upvotes: 2