所以,我的应用程序支持三个主题,每个主题具有不同的tintColors。我正在使用@EnvironmetObject跟踪更改。但是,我不能在SceneDelegate.swift文件中使用它,因为应用程序会崩溃。此外,accentColor不是一种选择,因为它不会改变警报tintColor。我该怎么做?
下面是一些代码:
SceneDelegate.swift 文件
下面是一些代码:
SceneDelegate.swift 文件
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
@EnvironmentObject var userData: UserData
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Create the SwiftUI view that provides the window contents.
let contentView = TasksView()
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView.environmentObject(UserData()))
self.window = window
window.makeKeyAndVisible()
window.tintColor = userData.selectedTheme.tintColor
}
}
这种方法会在应用启动时崩溃,因为它无法在其祖先中找到 @EnvironmentObject。
ContentView.swift 文件
struct ContentView: View {
@EnvironmentObject var userData: UserData
var body: some View {
NavigationView{
List(userData.tasks) { task in
TaskRow(taskTitle: task.title, taskDetail: task.detail)
}
.navigationBarTitle(Text("Tasks"), displayMode: .automatic)
.navigationBarItems(
leading: NavigationLink(destination: SettingsView(), label: {
Image(systemName: "gear").imageScale(.large)
}),
trailing: NavigationLink(destination: AddTaskView(), label: {
Image(systemName: "plus").imageScale(.large)
})
)
}.navigationViewStyle(StackNavigationViewStyle())
.accentColor(userData.selectedTheme.accentColor)
}
}
这种方法对我也不可行,因为它无法改变警报的“tintColor”(例如)。
图片
如果我使用accentColor,我就会得到这个结果
这是我想要实现的效果
SceneDelegate
中的代码,以及你所说的它不改变警告色调是什么意思? - Glenn PosadasUIButton.appearance()
也不起作用。Alert.Button
是一个结构体,不应该被子类化,它也不是一个View
,你无法更改它的颜色属性。 - Glenn PosadasUIView.appearance().tintColor = .green
将使 SwiftUI 警告框中的按钮变为绿色。 - Mike Taverne