I’ve noticed that there are a lot of UIView subclasses in my legacy project. Mostly the only reason of such a subclass is to split bigger view into custom subviews and provide layout for its subviews and delegation of UIButtons actions through the view delegate protocol. So I’m wondering, is it a correct design?
A very common reason to create a UIView subclass is so that one can specify a drawRect method to do some Core Graphics drawing into a view. Another reason might to implement touch delegates, such as if you want to do something within a specific view area too specialized for a gesture recognizer.
Partitioning objects (such as views) into logical groupings, possibly into a hierarchy, is usually considered good coding practice, as it helps isolates the scope of any changes or bugs.
If your view is just a container of other views, then you better use a regular (not subclassed) UIView. You compose the view (or load then nib) from a subclassed view controller.
Exceptions: when to subclass UIView:
- for custom drawing
- non standard touch responses (beyond the capabilities of the gesture recognizers)
In early iOS, there was no ViewController. Some things we might now do with a ViewController today were done by the view; it sounds like some of your view classes are doing things like that.
On the whole, it’s not a terrible code smell if the subclass is small. When the subclass gets too messy, sprout new classes to manage the aggregation (MyController) and delegation (MyViewDelegate) responsibilities.
In XCode, every UIButton, UiLabel are UIViews only those predefined UIViews, so when you want to add those to your ViewController, they will be added like:
[self.view addSubview:aView];
We can also create custom UIViews which allow you to design your own complex views like tableViews, GridViews, Charts and so on…
1
if you can manage all your view then there is no harm to keep number of subviews..
you can refer View hierarchy..
https://developer.apple.com/library/mac/Documentation/Cocoa/Conceptual/CocoaViewsGuide/WorkingWithAViewHierarchy/WorkingWithAViewHierarchy.html
In one of my project i had 10 subviews which were added based on my button click…
I searched and found there is no limitation given for subviews…