Created
October 14, 2024 07:52
-
-
Save Koshimizu-Takehito/e19b4600b145d01177b38004739e586e to your computer and use it in GitHub Desktop.
外観モードの変更にアニメーションをつける
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
struct ContentView: View { | |
@State var isDark = false | |
@State var currenct = ColorScheme.light | |
@Environment(\.colorScheme) var environment | |
var body: some View { | |
NavigationStack { | |
Form { | |
Toggle("Dark Mode", isOn: $isDark) | |
.listRowBackground(rowBackground) | |
} | |
.scrollContentBackground(.hidden) | |
.frame(maxWidth: .infinity, maxHeight: .infinity) | |
.background(background) | |
.navigationTitle("Color Scheme") | |
.environment(\.colorScheme, currenct) | |
.preferredColorScheme(currenct) | |
.onChange(of: environment, initial: true) { _, value in | |
isDark = value == .dark | |
} | |
.task(id: isDark) { | |
try? await Task.sleep(nanoseconds: 1_000_000_00) | |
withAnimation(.smooth(duration: 1.0)) { | |
currenct = isDark ? .dark : .light | |
} | |
} | |
} | |
} | |
} | |
extension ContentView { | |
fileprivate var rowBackground: some View { | |
#if os(iOS) | |
Color(.secondarySystemGroupedBackground) | |
#else | |
Color.clear | |
#endif | |
} | |
fileprivate var background: some ShapeStyle { | |
#if os(iOS) | |
Color(.systemGroupedBackground) | |
#elseif os(macOS) | |
Color(NSColor.windowBackgroundColor) | |
#else | |
.clear | |
#endif | |
} | |
} | |
#Preview { | |
#if os(macOS) | |
ContentView() | |
.frame(width: 400, height: 240) | |
#else | |
ContentView() | |
#endif | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Simulator.Screen.Recording.-.iPhone.16.Pro.-.2024-10-14.at.16.54.34.mp4