在 SwiftUI 应用程序中更改应用程序色调颜色的最佳方法是什么?
它由新的 SwiftUI 生命周期提供支持,因此我无法选择执行 self.?tintColor
尝试在这里搜索,但没有找到任何在 SwiftUI 生命周期应用程序中执行此操作的方法。
koe*_*oen 10
这无需 , 即可工作EnvironmentKey,并传播到应用程序中的所有视图:
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
.accentColor(.red) // pick your own color
}
}
}
Run Code Online (Sandbox Code Playgroud)
在为SceneDelegate.swift应用程序创建窗口的位置,您可以使用tintColor以下属性全局设置色调颜色UIWindow
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()
}
Run Code Online (Sandbox Code Playgroud)
编辑
在看到您想要将其用于新的 SwiftUI 后,您可以创建新的环境密钥:
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()
}
Run Code Online (Sandbox Code Playgroud)
然后在你的观点中你会这样使用它:
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)
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3895 次 |
| 最近记录: |