Search code examples
iphoneobjective-ciosglobaluicolor

What is wrong with my UIColor code?


I want to make a global UIColor value.

In AppDelegate.m I write

UIColor *fontcolor;

fontcolor = [UIColor colorWithRed:0.0 green:0.0 blue:1.0 alpha:1.0];

In MainViewController.m I write

extern UIColor *fontcolor;

[cell.textLabel setTextColor: fontcolor];

But my app crashes without any log.


Solution

  • First off, I'd like to understand why you'd be trying to create a global UIColor in your AppDelegate.m, if you could explain more as to why you're doing what you're doing that would be great!

    However, in the mean time, an issue with your actual UIColor code that I picked up on my travels.

    I always build my UIColor variables as follows. When it comes to the RGB style anyway.

    [UIColor colorWithRed:0.0f/255.0f green:0.0f/255.0f blue:255.0f/255.0f alpha:1.0f];
    

    The reason for this me doing this is due to the fact that that is how RGB formatting works everywhere else I look. It is a number out of 255.

    Now, as for actually creating a global variable of it, I don't see the point in my opinion. If it is solely to set UILabel color, there is no point in doing it globally.

    Whenever you have a UILabel you want to change the color of, I find it very simple to just do the following.

    [cell.textLabel setTextColor:[UIColor colorWithRed:0.0f/255.0f green:0.0f/255.0f blue:255.0f/255.0f alpha:1.0f]];
    

    Where textLabel is the main UILabel in a UITableViewCell.

    EDIT

    Just read through some of the comments. I see you are wanting to change the color depending on a user preference. Simply utilise NSUserDefaults to achieve this.

    The end result would be something like this.

    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"blue"]) {        
       [cell.textLabel setTextColor:[UIColor colorWithRed:120.0f/255.0f green:0.0f/255.0f blue:180.0f/255.0f alpha:1.0f]];
    } else {
       [cell.textLabel setTextColor:[UIColor colorWithRed:0.0f/255.0f green:0.0f/255.0f blue:255.0f/255.0f alpha:1.0f]];
    }