There are several use cases that can be applied to UIView
inheritance, such as:
- implementing a custom control
- extending
UIView
with methods that implement specific functionalities (although it can also be done by using a category
, although that works in a different way and usually applies to different use cases)
- group correlated views into a single view, to improve usage, expose a clean interface and deal with views management internally
- create a base view that you want to reuse in other
UIView
inherited classes, without having to implement the custom look and/or behavior on each subclass
Below some examples
Custom control - You want to implement a 4 states flat push button, which 'advances' to the next state on every tap. Each state is visually represented in a different way, for instance by changing the label, the border, and/or the color. Note: in this example it would be better to extend the UIControl
or UIButton
, which are both subclasses of UIView
Extension - You want a view that has a rounded border, a title and a body section, with the title having a bigger font and on inverted colors (white text on dark gray background).
Grouping - You have a panel where you want to display a user profile, with several labels and values (i.e. User Name: myusername), a profile picture, dynamically laid out.
Base Class - you have a set of views that share a common look, with a rounded border, a title at top right overlapping the border, and an internal panel where to lay out content. You create a UIView
subclass called SOMyPanelBaseView
, and then inherit other classes from it, automatically inheriting the look
In many cases (but not all) you can skip inheritance and implement everything in a view controller, but besides being a not good object oriented design (the view is highly tied to the view controller), it makes the view controller over complicated. By inheriting from a UIView
instead you implement the view functionalities in a separate class, and plug those functionalities into the view controller.
Also, an UIView
inherited class can be reused - whereas if you implement everything in the view controller, you can't unless you copy and paste code around.
To sum up, I think your question can be generalized as: why should I use inheritance in object oriented programming?
The same reasons behind using inheritance in OOP is the same as using it in a specific case, in our case for UIView
. The topic is described pretty well on wikipedia