How to Add a Dark Mode Toggle for iOS 18 - #30DaysOfSwift
2024-10-23 05:54:58 Author: hackernoon.com(查看原文) 阅读量:2 收藏

Day 11: Embrace the Night 🌙

For the eleventh post of the #30DaysOfSwift series, I am adding a Dark Mode Toggle to switch between Light/Dark modes in SwiftUI.

SwiftUI natively supports Dark Mode, and today, we'll create a sleek, minimalistic UI to let users toggle between the two themes.

Steps to Add a Dark Mode Toggle:

1. Create a Toggle Button:

Add a toggle switch in the settings view that allows users to manually switch between light and dark modes.

2. Customize the Appearance:

We'll implement a system that changes the app's color scheme using SwiftUI's @Environment(.colorScheme) modifier.

import SwiftUI

struct DarkModeToggleView: View { 

@State private var isDarkMode = false // State to track the mode

var body: some View {
    VStack {
        // Title Text
        Text("Dark Mode Toggle")
            .font(.largeTitle)
            .fontWeight(.bold)
            .padding()

        // Example image to showcase the mode effect
        Image(systemName: isDarkMode ? "moon.fill" : "sun.max.fill")
            .resizable()
            .scaledToFit()
            .frame(width: 100, height: 100)
            .foregroundColor(isDarkMode ? .yellow : .orange) // Custom color for each mode
            .padding()

        // Toggle switch with label
        Toggle(isOn: $isDarkMode) {
            Text(isDarkMode ? "Dark Mode" : "Light Mode")
                .font(.headline)
        }
        .toggleStyle(SwitchToggleStyle(tint: .blue)) // Beautiful blue accent color
        .padding()

    }
    // Apply the color scheme dynamically
    .preferredColorScheme(isDarkMode ? .dark : .light)
    .animation(.easeInOut, value: isDarkMode) // Smooth transition between modes
    .frame(maxWidth: .infinity, maxHeight: .infinity)
    .background(isDarkMode ? Color.black : Color.white) // Set background color based on mode
    .edgesIgnoringSafeArea(.all)
}
}

struct DarkModeToggleView_Previews: PreviewProvider { static var previews: some View { DarkModeToggleView() } }

Add this feature to your app, and give your users a sleek way to switch between Light and Dark Mode! 🌗

Happy Coding!

P.S. This series is becoming huge! You can read about all the stories by clicking on my profile.


文章来源: https://hackernoon.com/how-to-add-a-dark-mode-toggle-for-ios-18-30daysofswift?source=rss
如有侵权请联系:admin#unsafe.sh