Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
SwiftUI Change Status Bar Color with Custom Hosting Controller
//
// AppDelegate.swift
// StatusBarTest
//
// Created by hiroki on 2021/02/11.
//
import UIKit
import SwiftUI
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
let configuration = UISceneConfiguration()
configuration.delegateClass = SceneDelegate.self
return configuration
}
}
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let scene = (scene as? UIWindowScene) else { return }
window = UIWindow(windowScene: scene)
window?.rootViewController = StatusBarConfigurator().hostingController(rootView: ContentView())
window?.makeKeyAndVisible()
}
}
class StatusBarConfigurator: ObservableObject {
var statusBarStyle: UIStatusBarStyle = .default {
didSet {
_hostingController?.setNeedsStatusBarAppearanceUpdate()
}
}
private var _hostingController: UIViewController?
func hostingController<T: View>(rootView: T) -> UIViewController {
let hc = HostingController(rootView: rootView.environmentObject(self))
hc.configurator = self
_hostingController = hc
return hc
}
private class HostingController<T>: UIHostingController<T> where T: View {
weak var configurator: StatusBarConfigurator!
override var preferredStatusBarStyle: UIStatusBarStyle { configurator.statusBarStyle }
}
}
//
// ContentView.swift
// StatusBarTest
//
// Created by hiroki on 2021/02/11.
//
import SwiftUI
struct ContentView: View {
@EnvironmentObject var statusBarConfigurator: StatusBarConfigurator
var body: some View {
VStack(spacing: 30) {
Text("Status Bar Color Test")
.font(.title)
Button("Black") {
statusBarConfigurator.statusBarStyle = .darkContent
}
Button("White") {
statusBarConfigurator.statusBarStyle = .lightContent
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity) // 背景色をステータスバーまで広げるため
.background(Color.gray.ignoresSafeArea()) // ステータスバーの色をわかりやすくするために背景をグレーに
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment