I have a UIViewController
say viewControllerA which contains some view element like UIButton
, UILabel
etc. Now my question is should I create those view elements in a separate UIView
class and then add in UIViewController
, or should I create those view elements directly inside the UIViewController
. Accordingly to MVC isn't it appropriate to create view elements inside a separate UIView
class and then add this in UIViewController
?

- 4,261
- 3
- 32
- 60

- 3,668
- 9
- 43
- 56
-
this is purely depends upon your requirement – manujmv Nov 29 '13 at 05:44
-
Is there a reason why you are not creating these Buttons and labels in storyboard in xcode and then linking them to your VC class for actions and outlets? – Khaled Barazi Nov 29 '13 at 05:46
-
@manujmv But accordingly MVC isn't it appropriate to have all the view elements in a separate class? – russell Nov 29 '13 at 06:06
-
@Spectravideo328 infact i want to do it programatically. – russell Nov 29 '13 at 06:06
1 Answers
The standard place to build the view hierarchy in a UIViewController is in the -viewDidLoad
method. That method gets called whenever the UIViewController's view is created. The view controller's view will be loaded from the NIB/Storyboard if applicable; your outlets will be wired up; and then -viewDidLoad
is called for you to perform further customization:
- (void)viewDidLoad
{
[super viewDidLoad];
UILabel *aLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0,0.0,100.0,40.0)];
[self.view addSubView:aLabel];
}
In Cocoa/Cocoa Touch you don't always want to subclass everything the way you would in, say, Java. There are often other preferred means of extending the functionality in built-in classes such as Objective-C categories, delegation, and pre-defined properties.
It's certainly possible to do this sort of thing another way, but this is the most "Cocoa-like" way to do it. Actually, the most "Cocoa-like" way would be to create the view hierarchy in Interface Builder, but if you want to do it programmatically this is the usual way.

- 960
- 7
- 10