Changing background color in UIView
I have a problem with setting the background color UIView
. I am using the following code:
self.view.backgroundColor = [UIColor colorWithRed:0
green:0.675
blue:0.929
alpha:1];
This works great when I set the background color right at the start of the app, but when I want to update my background color after I launch the app from the notification center widget it doesn't change color.
EDIT - A few more details:
When the app is launched from the Action Center, the AppDelegate method is called, which stores the called URL scheme as "NSString" and calls another method where the background color needs to be updated.
I have verified that the method call is working fine.
My problem is that the color is not being updated even though the method is being called.
source to share
Update the color in the viewWillAppear
controller where your view is displayed. Set a breakpoint to make sure the code is called and the reference view is not nil
.
If you just want to "preserve" the color without displaying it, use NSUserDefaults
. You can only store primitives so you can do this for example.
// save
[[NSUserDefaults standardUserDefaults] setObject:@"0,0.675,0.929" forKey@"savedColor"];
// retrieve
NSString *colorString = [[NSUserDefaults standardUserDefaults] objectForKey:@"savedColor"];
NSArray *c = [colorString componentsSeparatedByString:@","];
CGFloat r = [c[0] floatValue];
CGFloat g = [c[1] floatValue];
CGFloat b = [c[2] floatValue];
UIColor *color = [UIColor colorWithRed:r green:g blue:b alpha:1];
Or maybe clearer and more succinct
// save
[[NSUserDefaults standardUserDefaults] setObject:
@{@"red" : @0, @"green" : @0.675, @"blue" : @0.929} forKey:@"savedColor"];
// retrieve
NSDictionary *c = [[NSUserDefaults standardUserDefaults] objectForKey@"savedColor"];
UIColor *color = [UIColor
colorWithRed:c[@"red"] green:c[@"green"] blue:c[@"blue"] alpha:1];
Now, you will apply all of this into convenience methods:
-(void)saveColorToUserDefaults:(UIColor*)color withKey:(NSString*)key {
CGFloat red, green, blue, alpha;
[color getRed:&red green:&green blue:&blue alpha:&alpha];
[[NSUserDefaults standardUserDefaults] setObject:
@{@"red": @(red), @"green" : @(green), @"blue" : @(blue), @"alpha" : @(alpha)}
forKey: key];
}
-(UIColor*)colorFromUserDefaultsWithKey:(NSString *)key {
NSDictionary *c = [[NSUserDefaults standardUserDefaults] objectForKey@"savedColor"];
return = [UIColor colorWithRed:c[@"red"] green:c[@"green"]
blue:c[@"blue"] alpha:c[@"alpha"]];
}
source to share