There are several apps on the App Store that have the option in the app to automatically switch to dark mode. I’m assuming there is an easy way to implement this, but I can’t seem to find anything about it when looking online. I just want to be able to have the user select an option that will automatically switch to a dark theme if it is after sunset but have the light theme during the day. Anyone know how to do this in swift?
Swift Automatically Switch App’s Theme At Sunset
1.3k Views Asked by firebolthappy At
2
There are 2 best solutions below
3
Krzysio
On
If you want to make your own, custom dark mode you can use traitCollectionDidChange to detect when iOS goes in and out of dark mode and then perform your customisation. This is only for iOS 13 and above.
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection) //always call this first
}
Related Questions in IOS
- Overlapping UICollectionView in storyboard
- Cannot pod spec lint because of undeclared type errors
- Is the transactionReceipt data present in dataWithContentsOfURL?
- UIWebView Screen Fitting Issue
- ZXingObjC encoding issues
- iOS: None of the valid provisioning profiles allowed the specific entitlements
- How to hide "Now playing url" in control center
- CloudKit: Preventing Duplicate Records
- Slow performance on ipad erasing image
- Swift code with multiple NSDateFormatter - optimization
- iOS 8.3 Safari crashes on input type=file
- TTTTimeIntervalFormatter always returns strings in English
- How do I add multiple in app purchases in Swift Spritekit?
- Setup code for xibs in iOS. -awakFromNb:
- iOS Voice Over only reads out the title of any alert views
Related Questions in SWIFT
- Overlapping UICollectionView in storyboard
- Cannot pod spec lint because of undeclared type errors
- Swift code with multiple NSDateFormatter - optimization
- How do I add multiple in app purchases in Swift Spritekit?
- cellForRowAtIndexPath and prepareForSegue return different label colors
- Getting this message in my console in xcode "Ignoring restoreCompletedTransactionsWithApplicationUsername: because already restoring transactions"?
- Change background of an Accessory View in a UITableViewCell
- fade in an bounce animation subview
- Create a PFObject and PFRelation after PFUser Sign Up
- Swift 2 - Pattern matching in "if"
- How do I give inputs through NSURL
- How do I add custom cells to TableView in Swift?
- UIWebView not loading URL in simulator
- Compiler complains that 'Expression resolved to unused function' when removing index in array of functions
- Cast from 'Int?' to unrelated type 'NSNumber' always fails
Related Questions in SWIFTUI
- Ternary operator inside NavigationLink SwiftUI
- Use ViewRouter in SwiftUI Project in Xcode 12
- SwiftUI Navigation View - Handling Size Classes over multiple views
- Is there any way to create a new Gesture in SwiftUI?
- SwiftUI extension to display Image in Alert()
- Get changes on button tapped using Combine and SwiftUI
- Does `ShapeStyle` inherit from `View`?
- Nested transitions / animations in SwiftUI
- How do I set an image in a cell class from a ImagePicker Controller
- How to disable minimum value of 0 in Slider?
- SwiftUI NavigationView issue with Parent-Child-Grandchild scenario when attempting grandchild previous next navigation
- SwiftUI strange tabbar behaviour with groups
- Picker in SwiftUI 2 .onChange() does not change UINavigationBar.appearance()
- SwiftUI Change Form Background
- SwiftUI image picker, url image from camera
Related Questions in THEMES
- Eclipse color highlighting broken
- Wrong Theme being applied to PreferenceActivity with xml reference
- "Use Theme.AppCompat theme with this activity" Exception
- PrefererenceFragment Material Theme with Support Library
- Unable to use the Sphinx Readability theme
- Translucent theme with material
- How to retrieve data from wordpress database in php and display on a page?
- Different theme for each language in Eclipse
- How to properly create a child theme structure
- Drupal Zen theme without compass
- How to properly apply styles to Child theme
- How can I add a gallery of photos to the Big Cartel NEAT Theme?
- Does "enable runtime themes" affect performance?
- tablesorter themes not working
- 100% exact Espresso theme for Sublime Text?
Related Questions in IOS-DARKMODE
- Why do dynamic colors from my colors catalogue do not work on my navigation bar?
- Submit apple store for review DarkMode UIUserInterfaceStyle key in info.plist
- DarkMode UIUserInterfaceStyle key in info.plist for ios 13 below versions
- SwiftUI ButtonStyle animation causes UI not to update in App Switcher snapshot when system appearance changes
- Tab Bar Controller: Icon and Colors when switching to dark mode
- Unable to change preview to dark mode in SwiftUI (Xcode12)
- overrideUserInterfaceStyle not working in AppDelegate
- Force ViewController light mode but keep WKWebView mode adaptable
- Testing Dark Mode using snapshot testing
- CALayer displaying wrong SFSymbol image for light / dark mode
- How to get explicitly light or dark color from ColorSet?
- Additional ColorScheme in Swift/SwiftUI beside Dark Mode and Light Mode
- UIUserInterfaceStyle key is not available in Info.plist in Xcode 12, how to disable Dark Mode in Xcode 12 from Info.plist?
- How to implement a color scheme switch with the system value option?
- Is there a way to observe a change between Dark and Light mode on iOS using Notifications instead of the standard Delegate function?
Trending Questions
- UIImageView Frame Doesn't Reflect Constraints
- Is it possible to use adb commands to click on a view by finding its ID?
- How to create a new web character symbol recognizable by html/javascript?
- Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)?
- Heap Gives Page Fault
- Connect ffmpeg to Visual Studio 2008
- Both Object- and ValueAnimator jumps when Duration is set above API LvL 24
- How to avoid default initialization of objects in std::vector?
- second argument of the command line arguments in a format other than char** argv or char* argv[]
- How to improve efficiency of algorithm which generates next lexicographic permutation?
- Navigating to the another actvity app getting crash in android
- How to read the particular message format in android and store in sqlite database?
- Resetting inventory status after order is cancelled
- Efficiently compute powers of X in SSE/AVX
- Insert into an external database using ajax and php : POST 500 (Internal Server Error)
Popular Questions
- How do I undo the most recent local commits in Git?
- How can I remove a specific item from an array in JavaScript?
- How do I delete a Git branch locally and remotely?
- Find all files containing a specific text (string) on Linux?
- How do I revert a Git repository to a previous commit?
- How do I create an HTML button that acts like a link?
- How do I check out a remote Git branch?
- How do I force "git pull" to overwrite local files?
- How do I list all files of a directory?
- How to check whether a string contains a substring in JavaScript?
- How do I redirect to another webpage?
- How can I iterate over rows in a Pandas DataFrame?
- How do I convert a String to an int in Java?
- Does Python have a string 'contains' substring method?
- How do I check if a string contains a specific word?
The most reliable – and by far the easiest – way to implement this is to plug into the system's dark mode setting, rather than rolling your own time-based system. This will also allow your users to make their own decision – if they want light mode all the time, or want to temporarily switch to dark mode in the middle of the day, your app will automatically work for them. And they'll thank you for it.
There are various ways you can manage this:
Use
Color's built-in definitions, such as .primary and .secondary, and when they don't satisfy, consider usinginit(UIColor)to convert some of UIKit's larger list of UI Element colors to work with SwiftUI.If you define your own colors in your Asset catalog and use them via the
Color("My Color Name")syntax, you can elect to set a dark mode variant to use (by changing theAppearancesetting fromNonetoAny, Dark).When the iOS system changes from light to dark and back, your color variants will get selected automatically. These might be a slight variation – e.g., a different shade of purple that looks better when working with dark colors – or it could be something that inverts completely (light gray to dark gray, for example).
If you need to make any more drastic changes – like changing line weights in dark mode – your views can find out whether dark mode is enabled by using the
colorSchemeenvironment variable:colorSchemewill be either.darkor.lightdepending on the phone settings.However, if you are insistent that you want to have control over light and dark mode instead of letting the system take on that responsibility, you can use the same environment value from step 3 and override it. For example:
In that example
MyView, and its children, will then behave as if dark mode is always on and everything else – auto-selection of colors from the asset catalog, etc. – will work.So if you wanted to, you could come up with your own time-based approach to determine whether to set the colorScheme environment to
.lightor.dark.However, I'd recommend again to let the system handle everything unless you have a very good reason not to.