在应用程序的两种配色方案之间切换?

Lix*_*ixu 3 objective-c

例如,我想要白天的所有视图(背景和标签)的浅色和晚上的深色.该应用程序将根据时间自动更改其颜色.此外,用户还可以在设置中切换到其他配色方案.这样做最有效的方法是什么?

开关中涉及多种颜色(背景和标签).

Ste*_*ord 6

我最近做过一些非常相似的事情; 应用程序需要各种用户可选择的配色方案.

主题

创建一个Theme类,其中包含每种颜色类型的属性.尽量不要描述具体的用法(submitButtonBackgroundColor),而是描述目的(这样你最终会得到更少的颜色定义):

extern NSString * const ThemeChanged;

@interface Theme : NSObject

+ (Theme *)currentTheme;
+ (void)setCurrentTheme:(Theme *)theme;

@property (nonatomic, strong) UIColor *backgroundColor;
@property (nonatomic, strong) UIColor *foregroundColor;
@property (nonatomic, strong) UIColor *darkerForegroundColor;
@property (nonatomic, strong) UIColor *lighterForegroundColor;
@property (nonatomic, strong) UIColor *highlightColor;

@end
Run Code Online (Sandbox Code Playgroud)

执行:

NSString * const ThemeChanged = @"ThemeChanged";

static Theme *_currentTheme = nil;

// Note this is not thread safe

@implementation Theme

+ (Theme *)currentTheme {
    return _currentTheme;
}

+ (void)setCurrentTheme:(Theme *)theme {
    _currentTheme = theme;

    [[NSNotificationCenter defaultCenter] postNotificationName:ThemeChanged object:nil];
}

@end
Run Code Online (Sandbox Code Playgroud)

然后可以使用您希望的每个方案(一个用于一天,一个用于夜晚)来实例化该类.

每个视图控制器都需要访问[Theme currentTheme]以检索颜色.它们(您的视图控制器)也可以注册为ThemeChanged通知的观察者,以便在您使用时更改主题时动态更新其视图的颜色setCurrentTheme:.

日/夜检测

至于基于一天的时间,你可以使用重复的自动更新NSTimer合理的间隔,查看当前的时间和呼叫setCurrentTheme:与您创建的黑暗的主题对象.

@interface DayNightHandler : NSObject
@property (nonatomic, strong) NSTimer *timer;

@end

@implementation DayNightHandler

- (instancetype)init
{
    self = [super init];
    if (self) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:1
                                                  target:self
                                                selector:@selector(checkTime)
                                                userInfo:nil
                                                 repeats:YES];
    }
    return self;
}

- (void)checkTime {
    NSDate *currentDate = [NSDate date];
    NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitHour | NSCalendarUnitMinute
                                                                   fromDate:currentDate];

    NSLog(@"%@",components);

    // Very crude
    if (components.hour >= 18 || components.hour <= 6) {
        // set dark theme
    } else {
        // set light theme
    }
}

@end
Run Code Online (Sandbox Code Playgroud)

您可能想要将粗略的日/夜检查换成更稳固的东西,这纯粹是一个旨在让您走上正确轨道的高级示例.