什么是在SwiftUI应用程序中更改应用程序色调颜色的最佳方法?
它由新的SwiftUI生命周期驱动,因此我没有执行self.?tintColor选项。
尝试在这里搜索,但没有找到在SwiftUI生命周期应用程序中执行此操作的方法。
它由新的SwiftUI生命周期驱动,因此我没有执行self.?tintColor选项。
尝试在这里搜索,但没有找到在SwiftUI生命周期应用程序中执行此操作的方法。
这个功能不需要 EnvironmentKey
,并且能够在应用程序中的所有视图中传播:
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
.accentColor(.red) // pick your own color
}
}
}
SceneDelegate.swift
中创建应用程序窗口时,可以使用 UIWindow
的 tintColor
属性全局设置色调颜色。let contentView = ContentView()
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
self.window?.tintColor = UIColor.red // Or any other color you want
window.makeKeyAndVisible()
}
编辑
在看到您想要为新的SwiftUI使用它之后,您可以创建新的EnvironmentKeys:
private struct TintKey: EnvironmentKey {
static let defaultValue: Color = Color.blue
}
extension EnvironmentValues {
var tintColor: Color {
get { self[TintKey.self] }
set { self[TintKey.self] = newValue }
}
}
@main
struct YourApp: App {
var body: some Scene {
WindowGroup {
ContentView().environment(\.tintColor, Color.red)
}
}
}
然后在您的视图中,您将像这样使用它:
struct ContentView: View {
@Environment(\.tintColor) var tintColor
var body: some View {
VStack {
Text("Hello, world!")
.padding()
Button(action: {}, label: {
Text("Button")
})
}.accentColor(tintColor)
}
}
.accentColor(.red)
了吗? - Itay Brenner@Environment(\.accentColor) var accentColor
- Itay Brenner enum MyColor: Identifiable, CaseIterable {
var id: String { UUID().uuidString }
case blue, green, orange, pink, purple, red, yellow
var currentColor: Color {
switch self {
case .blue:
return .blue
case .green:
return .green
case .orange:
return .orange
case .pink:
return .pink
case .purple:
return .purple
case .red:
return .red
case .yellow:
return .yellow
}
}
}
final class ViewModel: ObservableObject {
@Published
var isPresented = false
@Published
var myColor: MyColor = .blue
}
struct AppSettings: View {
@ObservedObject
var vm: ViewModel
var body: some View {
NavigationView {
Form {
Picker("Current color", selection: $vm.myColor) {
ForEach(MyColor.allCases) { color in
Label(
title: {
Text(color.currentColor.description.capitalized)
}, icon: {
Image(systemName: "circle.fill")
})
.tag(color)
.foregroundColor(color.currentColor)
}
}
}
.navigationBarItems(
trailing:
Button(
action: {
vm.isPresented.toggle()},
label: {
Text("Close")
}))
.navigationTitle("App settings")
}
}
}
struct ContentView: View {
@StateObject
private var vm = ViewModel()
var body: some View {
VStack {
Button(
action: {
vm.isPresented.toggle()
}, label: {
VStack {
Rectangle()
.fill(Color.accentColor)
.frame(width: 100, height: 100)
Text("Settings")
.font(.title)
}
})
}
.accentColor(vm.myColor.currentColor)
.sheet(
isPresented: $vm.isPresented) {
AppSettings(vm: vm)
.accentColor(vm.myColor.currentColor)
}
}
}