Skip to content

Instantly share code, notes, and snippets.

@Koshimizu-Takehito
Created October 14, 2024 07:52
Show Gist options
  • Save Koshimizu-Takehito/e19b4600b145d01177b38004739e586e to your computer and use it in GitHub Desktop.
Save Koshimizu-Takehito/e19b4600b145d01177b38004739e586e to your computer and use it in GitHub Desktop.
外観モードの変更にアニメーションをつける
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
}
@Koshimizu-Takehito
Copy link
Author

Simulator.Screen.Recording.-.iPhone.16.Pro.-.2024-10-14.at.16.54.34.mp4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment