Skip to content

Commit

Permalink
Initial source
Browse files Browse the repository at this point in the history
  • Loading branch information
markgravity committed Jan 18, 2024
0 parents commit 0677aa2
Show file tree
Hide file tree
Showing 8 changed files with 293 additions and 0 deletions.
8 changes: 8 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
.DS_Store
/.build
/Packages
xcuserdata/
DerivedData/
.swiftpm/configuration/registries.json
.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
.netrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 MarkG

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
24 changes: 24 additions & 0 deletions Package.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// swift-tools-version: 5.9
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
name: "StatusBarStylist",
platforms: [.iOS(.v14), .macOS(.v13)],
products: [
// Products define the executables and libraries a package produces, making them visible to other packages.
.library(
name: "StatusBarStylist",
targets: ["StatusBarStylist"]),
],
targets: [
// Targets are the basic building blocks of a package, defining a module or a test suite.
// Targets can depend on other targets in this package and products from dependencies.
.target(
name: "StatusBarStylist"),
.testTarget(
name: "StatusBarStylistTests",
dependencies: ["StatusBarStylist"]),
]
)
66 changes: 66 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# StatusBarStylist

StatusBarStylist is a framework to supports changing the Status Bar style with natural SwiftUI syntax.

Thank [Philip Trauner](https://stackoverflow.com/a/71458976/10270556) for this source code and idea.

## Installation
Requirements iOS 14+

### Swift Package Manager
1. In Xcode, open your project and navigate to File → Swift Packages → Add Package Dependency.
2. Paste the repository URL (https://github.com/markgravity/StatusBarStylist) and click Next.
3. For Rules, select version.
4. Click Finish.

### Swift Package
```swift
.package(url: "https://github.com/markgravity/StatusBarStylist", .upToNextMajor(from: "1.0.0"))
```

## Usage

In your ```@main``` App file, simply wrap your main view in a ```RootView```.

```swift
@main
struct ProjectApp: App {
var body: some Scene {
WindowGroup {
RootView {
ContentView() // Change your content here 👈
}
}
}
}
```

### Example
Use the ```.statusBarStyle(_ style: UIStatusBarStyle)``` method on a View.
```swift
struct ContentView: View {
var body: some View {
TabView {
// Tab 1 will have a light status bar
Color.black
.edgesIgnoringSafeArea(.all)
.overlay(Text("Light Status Bar").foregroundColor(.white))
.statusBarStyle(.lightContent) // set status bar style here
.tabItem { Text("Tab 1") }

// Tab 2 will have a dark status bar
Color.white
.edgesIgnoringSafeArea(.all)
.overlay(Text("Dark Status Bar"))
.statusBarStyle(.darkContent) // set status bar style here
.tabItem { Text("Tab 2") }
}
}
}
````

## Contribute
You can contribute to this project by helping me solve any [reported issues or feature requests](https://github.com/markgravity/StatusBarStylist/issues) and creating a pull request.

## License
StatusBarStylist is released under the [MIT License](LICENSE).
28 changes: 28 additions & 0 deletions Sources/StatusBarStylist/Interposed.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
//
// Interposed.swift
//
//
// Created by MarkG on 18/01/2024.
//

import SwiftUI

enum Interposed {

case pending
case successful
case failed
}

struct InterposedKey: EnvironmentKey {

static let defaultValue: Interposed = .pending
}

extension EnvironmentValues {

var interposed: Interposed {
get { self[InterposedKey.self] }
set { self[InterposedKey.self] = newValue }
}
}
126 changes: 126 additions & 0 deletions Sources/StatusBarStylist/StatusBarStylist.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
// The Swift Programming Language
// https://docs.swift.org/swift-book

import SwiftUI

extension UIApplication {

var keyWindow: UIWindow? {
connectedScenes
.compactMap { $0 as? UIWindowScene }
.flatMap(\.windows)
.first {
$0.isKeyWindow
}
}
}

extension UIViewController {

enum Holder {
static var statusBarStyleStack: [UIStatusBarStyle] = .init()
}

func interpose() -> Bool {
let sel1: Selector = #selector(
getter: preferredStatusBarStyle
)
let sel2: Selector = #selector(
getter: preferredStatusBarStyleModified
)

let original = class_getInstanceMethod(Self.self, sel1)
let new = class_getInstanceMethod(Self.self, sel2)

if let original = original, let new = new {
method_exchangeImplementations(original, new)

return true
}

return false
}

@objc dynamic var preferredStatusBarStyleModified: UIStatusBarStyle {
Holder.statusBarStyleStack.last ?? .default
}
}

struct StatusBarStyle: ViewModifier {

@Environment(\.interposed) private var interposed

let statusBarStyle: UIStatusBarStyle
let animationDuration: TimeInterval

private func setStatusBarStyle(_ statusBarStyle: UIStatusBarStyle) {
UIViewController.Holder.statusBarStyleStack.append(statusBarStyle)

UIView.animate(withDuration: animationDuration) {
UIApplication.shared.keyWindow?.rootViewController?.setNeedsStatusBarAppearanceUpdate()
}
}

func body(content: Content) -> some View {
content
.onAppear {
setStatusBarStyle(statusBarStyle)
}
.onChange(of: statusBarStyle) {
_ = UIViewController.Holder.statusBarStyleStack.removeLast()
setStatusBarStyle($0)
}
.onDisappear {
_ = UIViewController.Holder.statusBarStyleStack.removeLast()

UIView.animate(withDuration: animationDuration) {
UIApplication.shared.keyWindow?.rootViewController?.setNeedsStatusBarAppearanceUpdate()
}
}
// Interposing might still be pending on initial render
.onChange(of: interposed) { _ in
UIView.animate(withDuration: animationDuration) {
UIApplication.shared.keyWindow?.rootViewController?.setNeedsStatusBarAppearanceUpdate()
}
}
}
}

public extension View {

func statusBarStyle(
_ statusBarStyle: UIStatusBarStyle,
animationDuration: TimeInterval = 0.3
) -> some View {
modifier(StatusBarStyle(statusBarStyle: statusBarStyle, animationDuration: animationDuration))
}
}

public struct RootView<Content>: View where Content: View {

@Environment(\.scenePhase) var scenePhase
@State var interposed: Interposed = .pending
@ViewBuilder let content: () -> Content
var interposeLock = NSLock()

public var body: some View {
content()
.environment(\.interposed, interposed)
.onChange(of: scenePhase) { phase in
if case .active = phase {
interposeLock.lock()
if case .pending = interposed,
case true = UIApplication.shared.keyWindow?.rootViewController?.interpose() {
interposed = .successful
} else {
interposed = .failed
}
interposeLock.unlock()
}
}
}

public init(@ViewBuilder content: @escaping () -> Content) {
self.content = content
}
}
12 changes: 12 additions & 0 deletions Tests/StatusBarStylistTests/StatusBarStylistTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import XCTest
@testable import StatusBarStylist

final class StatusBarStylistTests: XCTestCase {
func testExample() throws {
// XCTest Documentation
// https://developer.apple.com/documentation/xctest

// Defining Test Cases and Test Methods
// https://developer.apple.com/documentation/xctest/defining_test_cases_and_test_methods
}
}

0 comments on commit 0677aa2

Please sign in to comment.