How can I check whether dark mode is enabled in iOS/iPadOS?

前端 未结 16 1509
囚心锁ツ
囚心锁ツ 2020-12-08 09:41

Starting from iOS/iPadOS 13, a dark user interface style is available, similar to the dark mode introduced in macOS Mojave. How can I check whether the user has enabled the

16条回答
  •  旧时难觅i
    2020-12-08 10:09

    Objective C

    To detect when dark mode is enabled or disabled via the Control Centre use an "appDidBecomeActive" notification that will be triggered when you return to your app.

    //----------------------------------------------------------------------------
    //                          viewWillAppear
    //----------------------------------------------------------------------------
    - (void)viewWillAppear {
        [super viewWillAppear];
    
        [[NSNotificationCenter defaultCenter]addObserver:self
                                       selector:@selector(appDidBecomeActive:)
                                       name:UIApplicationDidBecomeActiveNotification
                                       object:nil];
    
    }
    

    Don't forget to remove it when you're finished:

    //------------------------------------------------------------------------------------
    //                    viewWillDisappear
    //------------------------------------------------------------------------------------
    - (void)viewWillDisappear:(BOOL)animated
    {
        [super viewWillDisappear:animated];
    
        [[NSNotificationCenter defaultCenter] removeObserver:self        
                                     name:UIApplicationDidBecomeActiveNotification 
                                     object:nil];
    
    }
    

    Do what ever you need to when dark mode changes:

    //----------------------------------------------------------------------------
    //                          appDidBecomeActive
    //----------------------------------------------------------------------------
    -(void)appDidBecomeActive:(NSNotification*)note {
        if (@available(iOS 13.0, *)) {
            if( self.traitCollection.userInterfaceStyle == UIUserInterfaceStyleDark ){
                //dark mode
            }
            else {
                //not dark mode
            }
        }
        else {
            //fall back for older versions
        }
    }
    

提交回复
热议问题