My project is design a View with numerous label, image, textField without storyboard or Nib. Do I need manually alloc and add every single thing to the view? I think this is very overkill but I have no idea how to do it any other way. Example:
UILabel *firstLabel =[UILabel alloc] init];
firstLabel.frame = (0,x,20,10) ;
firstLabel.text = ...;
firstLabel.font = ...;
firstLabel.textColor = ...;
.................
[self.view addSubView:firstLabel];
UILabel *secondLabel =[UIlabel alloc] init];
secondLabel.frame = (0,y,20,10);
secondLabel.text = ...;
secondLabel.font = ...;
secondLabel.textColor = ...;
.................
[self.view addSubView:secondLabel];
UILabel *thirdLabel =[UIlabel alloc] init];
thirdLabel.frame = (0,z,20,10);
thirdLabel.text = ...;
thirdLabel.font = ...;
thirdLabel.textColor = ...;
.................
[self.view addSubView:thirdLabel];
Should I put all of them in viewDidLoad
or loadView
or init
method?
Or I just need make a method for CreatLabel
and use it again and again? How to do it?
If you're programmatically creating view from scratch, you'd do that in
loadView
. (See Creating a View Programmatically.) If, however, you have NIB/storyboard for the top level view and you are merely adding subviews, then you could do that inviewDidLoad
.Regarding the creation of a bunch of labels, yes, you could use subroutine. Or, assuming there is a regular pattern that dictates where these are positioned, you might even use a
for
loop in which you increment they
coordinate or build the constraints. (You can save references to these views in an array or usetag
values to keep track of them.) But however you do it, yes, you'd want to minimize the amount of repeated code you write (simplifying life from a maintenance perspective, if nothing else).