View+Keyboard.swift (2978B)
1 // MIT License 2 // Copyright Codelaby https://stackoverflow.com/users/3464919/codelaby 3 // 4 // Permission is hereby granted, free of charge, to any person obtaining a copy of this software 5 // and associated documentation files (the "Software"), to deal in the Software without restriction, 6 // including without limitation the rights to use, copy, modify, merge, publish, distribute, 7 // sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is 8 // furnished to do so, subject to the following conditions: 9 // 10 // The above copyright notice and this permission notice shall be included in all copies or 11 // substantial portions of the Software. 12 // 13 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING 14 // BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 15 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 16 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 17 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 18 // 19 import Foundation 20 import SwiftUI 21 import Combine 22 23 public extension View { 24 /// Sets an environment value for keyboardShowing 25 /// Access this in any child view with 26 /// @Environment(\.keyboardShowing) var keyboardShowing 27 func addKeyboardVisibilityToEnvironment() -> some View { 28 modifier(KeyboardVisibility()) 29 } 30 } 31 32 private struct KeyboardShowingEnvironmentKey: EnvironmentKey { 33 static let defaultValue: Bool = false 34 } 35 36 extension EnvironmentValues { 37 var keyboardShowing: Bool { 38 get { self[KeyboardShowingEnvironmentKey.self] } 39 set { self[KeyboardShowingEnvironmentKey.self] = newValue } 40 } 41 } 42 43 private final class KeyboardMonitor: ObservableObject { 44 @Published var isKeyboardShowing: Bool = false 45 private var cancellables = Set<AnyCancellable>() 46 47 init() { 48 NotificationCenter.default.publisher(for: UIResponder.keyboardWillShowNotification) 49 .map { _ in true } 50 .assign(to: \.isKeyboardShowing, on: self) 51 .store(in: &cancellables) 52 53 NotificationCenter.default.publisher(for: UIResponder.keyboardWillHideNotification) 54 .map { _ in false } 55 .assign(to: \.isKeyboardShowing, on: self) 56 .store(in: &cancellables) 57 } 58 } 59 60 private struct KeyboardVisibility: ViewModifier { 61 @StateObject private var keyboardMonitor = KeyboardMonitor() 62 63 fileprivate func body(content: Content) -> some View { 64 content 65 .environment(\.keyboardShowing, keyboardMonitor.isKeyboardShowing) 66 } 67 } 68 69 // Usage 70 // App 71 // WindowGroup { 72 // ContentView() 73 // .addKeyboardVisibilityToEnvironment() 74 // 75 // View 76 // @Environment(\.keyboardShowing) var keyboardShowing 77 // ... 78 // Text("Keyboard present: \(keyboardShowing.description)" )