Last active
October 27, 2019 18:38
-
-
Save cenkbilgen/630465f5d3755405128ea9bfa07c992c to your computer and use it in GitHub Desktop.
Extension for SwiftUI that reports the current keyboard height to Views through an EnvironmentVariable (modify to report any other notification).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// EnvironmentVariables.swift | |
// PlaylogR | |
// | |
// Created by Cenk Bilgen on 2019-10-12. | |
// Copyright © 2019 Cenk Bilgen. All rights reserved. | |
// | |
import SwiftUI | |
import UIKit | |
// Custom Environment Variables | |
// For example have a View's property bound to the current keyboard height like: | |
// @Environment(\.keyboardHeight) var keyboardHeight: CGFloat | |
// MARK: Add new properties to EnvironmentValues | |
extension EnvironmentValues { | |
var keyboardHeight : CGFloat { | |
get { EnvironmentObserver.shared.keyboardHeight } | |
} | |
} | |
// MARK: Pass notifications from UIResponder (or wherever) to set properties in EnvironmentValues | |
class EnvironmentObserver { | |
static let shared = EnvironmentObserver() | |
var keyboardHeight: CGFloat = 0 { | |
didSet { print("Keyboard height \(keyboardHeight)") } | |
} | |
init() { | |
// MARK: Keyboard Events | |
NotificationCenter.default.addObserver(forName: UIResponder.keyboardDidHideNotification, object: nil, queue: OperationQueue.main) { [weak self ] (notification) in | |
self?.keyboardHeight = 0 | |
} | |
let handler: (Notification) -> Void = { [weak self] notification in | |
guard let userInfo = notification.userInfo else { return } | |
guard let frame = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else { return } | |
// From Apple docs: | |
// The rectangle contained in the UIKeyboardFrameBeginUserInfoKey and UIKeyboardFrameEndUserInfoKey properties of the userInfo dictionary should be used only for the size information it contains. Do not use the origin of the rectangle (which is always {0.0, 0.0}) in rectangle-intersection operations. Because the keyboard is animated into position, the actual bounding rectangle of the keyboard changes over time. | |
self?.keyboardHeight = frame.size.height | |
} | |
NotificationCenter.default.addObserver(forName: UIResponder.keyboardDidShowNotification, object: nil, queue: OperationQueue.main, using: handler) | |
NotificationCenter.default.addObserver(forName: UIResponder.keyboardDidChangeFrameNotification, object: nil, queue: OperationQueue.main, using: handler) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment