Search code examples
iosuicolorviewdidload

ios - Wanting to clean up my viewDidLoad Method


.

Hi,

I am wanting to clean up my viewDidLoad method as I it is growing in number of lines of code and it is getting messy.

Now my UI is build programmatically, because I want to learn that way of doing things.

So I read on this SO Post that I can set the UI items in a seperate -9void) method and then link to that void by using [self method]

Now when I use that way, it does not seem to work for me.

like, if I want to set the back ground color this will work:

- (void)viewDidLoad
 {
[super viewDidLoad];

self.view.backgroundColor = [UIColor colorWithRed:0.0 green:0.2 blue:0.38 alpha:1.0];
}

but this does not:

- (void)viewDidLoad
{
[super viewDidLoad];

[self backgroundColor];


// Do any additional setup after loading the view.
}

-(void)backgroundColor
{
UIView *backgroundView = [[UIView alloc] init]; 

backgroundView.backgroundColor = [UIColor colorWithRed:0.0 green:0.2 blue:0.38  alpha:1.0];
}

Am I misunderstanding this??

Thanks in Advance:-)


Solution

  • I think you're misunderstanding the nature of views/view controllers.

    In this line:

    self.view.backgroundColor = [UIColor colorWithRed:0.0 green:0.2 blue:0.38 alpha:1.0];
    

    self refers to the view controller you are loading, and view refers to the view that is owned by that view controller. So when you set self.view.backgroundColor, you are setting the background color for the view that will be presented by the view controller you are displaying. Therefore that works.

    Your other method, on the other hand, doesn't do that:

    UIView *backgroundView = [[UIView alloc] init]; 
    

    That line creates an entirely new UIView instance, and sets its background color. This is a brand new view, and is NOT the same view which is referenced earlier by self.view.

    If you really want to have a separate function that changes the background color for you, write it like this:

    -(void) setBackgroundColor
    {
       self.view.backgroundColor = [UIColor colorWithRed:0.0 green:0.2 blue:0.38 alpha:1.0];
    }
    

    Then you're actually modifying the view that belongs to the view controller, and the change should actually display.


    I would also suggest that this function isn't very useful; you're creating a function that encapsulates a single line of code that will never change. There's really not much point in making a function for that. A more useful implementation might be:

    -(void) setBackgroundColor:(UIColor)newColor
    {
       self.view.backgroundColor = newColor;
    }
    

    To use this method, you would write the following line in your viewDidLoad method:

    [self setBackgroundColor:[UIColor colorWithRed:0.0 green:0.2 blue:0.38 alpha:1.0]];
    

    And then you could call setBackgroundColor again whenever you wanted, to change the background color to different values.