2

I wonder how to add UI elements programatically to existing nib files.

If I create a view programatically in loadView method and I add code like the following, the label displays correctly.

self.view = [[UIView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame];

UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(0,2,150,100)];

[self.view addView:lbl];

But how to add the label to an existing nib file?

1
  • 1
    You need to use viewDidLoad which is called after the view has finished loading (from the nib). You only use the loadView method if you are setting up your view completely in code. Commented Feb 7, 2012 at 11:30

3 Answers 3

2

As Paul.s pointed out, you need to perform your custom code in viewDidLoad method.

From Apple documentation.

This method is called after the view controller has loaded its associated views into memory. This method is called regardless of whether the views were stored in a nib file or created programmatically in the loadView method. This method is most commonly used to perform additional initialization steps on views that are loaded from nib files.

So, in your controller you could do this:

- (void)viewDidLoad
{
   [super viewDidLoad];

   // your other views here

   // call addSubview method on self.view
}

Why do you do this? Because here you are sure that view has loaded in memory and outlets has been set correctly.

On the contrary, about loadView method

If you override this method in order to create your views manually, you should do so and assign the root view of your hierarchy to the view property. (The views you create should be unique instances and should not be shared with any other view controller object.) Your custom implementation of this method should not call super.

An example could be:

- (void)loadView
{
    CGRect applicationFrame = [[UIScreen mainScreen] applicationFrame];
    UIView *contentView = [[UIView alloc] initWithFrame:applicationFrame];
    contentView.backgroundColor = [UIColor whiteColor];

    self.view = contentView; 

    // call addSubview method on self.view
}

I suggest you to read View Controller Programming Guide for iOS.

Hope it helps.

Sign up to request clarification or add additional context in comments.

Comments

1

AFAIK, to modify nib file programmatically is not possible.

You can add view into viewDidLoad of UIViewController method.

Comments

1

Inside viewDidLoad

UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(0,2,150,100)];
[self.view addSubView:lbl];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.