在SwiftUI应用程序中更改应用程序颜色的最佳方法是什么?
它由新的SwiftUI生命周期提供动力,因此我没有执行自我的选项。?tintColor
另外,如何实现此菜单?
(猜测它正在使用选择器和表单,但我无法在颜色名称旁边添加圆圈)
尝试在此处搜索,但是在SwiftUI生命周期应用中找不到任何方法。
答案 0 :(得分:2)
在创建应用程序窗口的SceneDelegate.swift
中,您可以使用tintColor
的{{1}}属性全局设置色调颜色
UIWindow
修改
看到您希望新的SwiftUI使用它之后,您可以创建新的EnvironmentKeys:
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()
}
然后在您的视图中,您将像这样使用它:
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)
}
}
}
答案 1 :(得分:0)
Ariel, 在此实施中, 您可以在整个应用程序生命周期中选择和使用“ accentColor”。但是,如果您想永久保留价值, 你应该考虑一个解决方案, 我希望你是一个聪明的人...
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)
}
}
}