Reputation: 4028
I have many custom View in my project ( UIView's subclass). And I need to override init
method.
I just want to override init(frame: CGRect)
method. And I don't want to write the same code init?(coder
in many UIView subclasses again and again.
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
And I add an extension to UIView, then OK.
extension UIView{
convenience init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
The problem occurs, when I custom UITableView class.
class Table: UITableView {
override init(frame: CGRect, style: UITableView.Style) {
super.init(frame: frame, style: style)
}
Xcode tips firstly,
'required' initializer 'init(coder:)' must be provided by subclass of 'UITableView'
class Table: UITableView {
override init(frame: CGRect, style: UITableView.Style) {
super.init(frame: frame, style: style)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
Xcode tips secondly,
Declaration 'init(coder:)' cannot override more than one superclass declaration
How to fix it?
Upvotes: 1
Views: 733
Reputation: 301
You can inherit your CustomTableView class from a BaseTableView Class which is a subclass of UITableView. BaseTableView class will contain both initialiser method of UITableView. Eg:
class BaseTableView: UITableView {
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(frame: CGRect, style: UITableView.Style) {
super.init(frame: frame, style: style)
}
}
Then your custom classes are inherited from BaseTableView class with a convenience override method of init(frame:...
class Table1: BaseTableView {
convenience override init(frame: CGRect, style: UITableView.Style) {
self.init(frame: frame, style: style)
}
}
class Table2: BaseTableView {
convenience override init(frame: CGRect, style: UITableView.Style) {
self.init(frame: frame, style: style)
}
}
we use convenience override init to convey that this is a convenience init that has the same signature as the designated initializer in the superclass.
Upvotes: 0
Reputation: 119716
Because convenience init
and required init
conflicted. You can not have more than one implementation for an initializer.
Upvotes: 0