iOS dark mode adaptation

Not suitable for dark mode

Add a new field directly in info

User Interface Style

Set the value to


Adapt to dark mode

You don't need to add the field in info to match the dark mode

But you need to add the following method to each UIWindow, uiviewcontroller and uiview

-(void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection

In this method, judge and change the color of all elements in the current interface

I made a single example to save all colors in the application separately

There are also two ways to change all colors to light or dark

In fact, it is a Color. Light Color is a Color value, while dark Color is another Color value. An application can define multiple colors

All colors of the application are taken from this single example

When the time comes, just refresh the interface

-(void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection
    [super traitCollectionDidChange: previousTraitCollection];
    if (@available(iOS 13.0, *))
        if(UITraitCollection.currentTraitCollection.userInterfaceStyle == UIUserInterfaceStyleDark)
            [[Color darkColor] setDarkColorArray];
            LRLog(@"Dark mode");
            [[Color darkColor] setBrightColorArray];
            LRLog(@"Normal mode");
        UIWindow* window = [[[UIApplication sharedApplication] delegate] window];
        [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[Color darkColor].dataColor2,NSFontAttributeName:[UIFont systemFontOfSize:18]}];
        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:[Color darkColor].backColor] forBarMetrics:(UIBarMetricsDefault)];
        [self.navigationController.navigationBar setShadowImage:[UIImage imageWithColor:[Color darkColor].backColor]];
        [self.navigationController.navigationBar setBarTintColor:[Color darkColor].backColor];
        window.backgroundColor=[Color darkColor].backColor;
        self.view.backgroundColor=[Color darkColor].backColor;

Demo address

Tags: iOS github

Posted on Wed, 25 Mar 2020 08:12:39 -0700 by champoi