-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathKeyboardObserver.swift
More file actions
323 lines (251 loc) · 10.5 KB
/
KeyboardObserver.swift
File metadata and controls
323 lines (251 loc) · 10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
import UIKit
/// Publicly exposes the current frame provider for consumers
/// that enable `KeyboardAdjustmentMode.custom` and need to calculate
/// their own content insets.
public protocol KeyboardCurrentFrameProvider {
func currentFrame(in view : UIView) -> KeyboardFrame?
}
public enum KeyboardFrame : Equatable {
/// The current frame does not overlap the current view at all.
case nonOverlapping
/// The current frame does overlap the view, by the provided rect, in the view's coordinate space.
case overlapping(frame: CGRect)
}
extension KeyboardObserver: KeyboardCurrentFrameProvider {}
@_spi(ListableKeyboard)
public protocol KeyboardObserverDelegate : AnyObject {
func keyboardFrameWillChange(
for observer: KeyboardObserver,
animationDuration: Double,
animationCurve: UIView.AnimationCurve
)
}
/**
Encapsulates listening for system keyboard updates, plus transforming the visible frame of the keyboard into the coordinates of a requested view.
You use this class by providing a delegate, which receives callbacks when changes to the keyboard frame occur. You would usually implement
the delegate somewhat like this:
```
func keyboardFrameWillChange(
for observer : KeyboardObserver,
animationDuration : Double,
options : UIView.AnimationOptions
) {
UIView.animate(withDuration: animationDuration, delay: 0.0, options: options, animations: {
// Use the frame from the keyboardObserver to update insets or sizing where relevant.
})
}
```
Notes
-----
iOS Docs for keyboard management:
https://developer.apple.com/library/archive/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html
*/
@_spi(ListableKeyboard)
public final class KeyboardObserver {
/// The global shared keyboard observer. Why is it a global shared instance?
/// We can only know the keyboard position via the keyboard frame notifications.
///
/// If a keyboard observing view is created while a keyboard is already on-screen, we'd have no way to determine the
/// keyboard frame, and thus couldn't provide the correct content insets to avoid the visible keyboard.
///
/// Thus, the `shared` observer is set up on app startup
/// (see `SetupKeyboardObserverOnAppStartup.m`) to avoid this problem.
public static let shared: KeyboardObserver = KeyboardObserver(center: .default)
/// Allow logging to the console if app startup-timed shared instance startup did not
/// occur; this could cause bugs for the reasons outlined above.
fileprivate static var didSetupSharedInstanceDuringAppStartup = false
private let center: NotificationCenter
private(set) var delegates: [Delegate] = []
struct Delegate {
private(set) weak var value: KeyboardObserverDelegate?
}
//
// MARK: Initialization
//
public init(center: NotificationCenter) {
self.center = center
/// We need to listen to both `will` and `keyboardDidChangeFrame` notifications. Why?
///
/// When dealing with an undocked or floating keyboard, moving the keyboard
/// around the screen does NOT call `willChangeFrame`; only `didChangeFrame` is called.
///
/// Before calling the delegate, we compare `old.endingFrame != new.endingFrame`,
/// which ensures that the delegate is notified if the frame really changes, and
/// prevents duplicate calls.
self.center.addObserver(
self,
selector: #selector(keyboardFrameChanged(_:)),
name: UIWindow.keyboardWillChangeFrameNotification,
object: nil
)
self.center.addObserver(
self,
selector: #selector(keyboardFrameChanged(_:)),
name: UIWindow.keyboardDidChangeFrameNotification,
object: nil
)
}
private var latestNotification: NotificationInfo?
//
// MARK: Delegates
//
public func add(delegate: KeyboardObserverDelegate) {
if delegates.contains(where: { $0.value === delegate }) {
return
}
delegates.append(Delegate(value: delegate))
removeDeallocatedDelegates()
}
public func remove(delegate: KeyboardObserverDelegate) {
delegates.removeAll {
$0.value === delegate
}
removeDeallocatedDelegates()
}
private func removeDeallocatedDelegates() {
delegates.removeAll {
$0.value == nil
}
}
//
// MARK: Handling Changes
//
/// How the keyboard overlaps the view provided. If the view is not on screen (eg, no window),
/// or the observer has not yet learned about the keyboard's position, this method returns nil.
public func currentFrame(in view: UIView) -> KeyboardFrame? {
guard let window = view.window else {
return nil
}
guard let notification = latestNotification else {
return nil
}
let screen = notification.screen ?? window.screen
let frame = screen.coordinateSpace.convert(
notification.endingFrame,
to: view
)
if frame.intersects(view.bounds) {
return .overlapping(frame: frame)
} else {
return .nonOverlapping
}
}
//
// MARK: Receiving Updates
//
private func receivedUpdatedKeyboardInfo(_ new: NotificationInfo) {
let old = latestNotification
latestNotification = new
/// Only communicate a frame change to the delegate if the frame actually changed.
if let old = old, old.endingFrame == new.endingFrame {
return
}
delegates.forEach {
$0.value?.keyboardFrameWillChange(
for: self,
animationDuration: new.animationDuration,
animationCurve: new.animationCurve
)
}
}
//
// MARK: Notification Listeners
//
@objc private func keyboardFrameChanged(_ notification: Notification) {
do {
let info = try NotificationInfo(with: notification)
receivedUpdatedKeyboardInfo(info)
} catch {
assertionFailure("Could not read system keyboard notification: \(error)")
}
}
}
extension KeyboardObserver {
struct NotificationInfo: Equatable {
var endingFrame: CGRect = .zero
var animationDuration: Double = 0.0
var animationCurve: UIView.AnimationCurve = .easeInOut
/// The `UIScreen` that the keyboard appears on.
///
/// This may influence the `KeyboardFrame` calculation when the app is not in full screen,
/// such as in Split View, Slide Over, and Stage Manager.
///
/// - note: In iOS 16.1 and later, every `keyboardWillChangeFrameNotification` and
/// `keyboardDidChangeFrameNotification` is _supposed_ to include a `UIScreen`
/// in a the notification, however we've had reports that this isn't always the case (at least when
/// using the iOS 16.1 simulator runtime). If a screen is _not_ included in an iOS 16.1+ notification,
/// we do not throw a `ParseError` as it would cause the entire notification to be discarded.
///
/// [Apple Documentation](https://developer.apple.com/documentation/uikit/uiresponder/1621623-keyboardwillchangeframenotificat)
var screen: UIScreen?
init(with notification: Notification) throws {
guard let userInfo = notification.userInfo else {
throw ParseError.missingUserInfo
}
guard let endingFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else {
throw ParseError.missingEndingFrame
}
self.endingFrame = endingFrame
guard let animationDuration = (userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue else {
throw ParseError.missingAnimationDuration
}
self.animationDuration = animationDuration
guard let curveValue = (userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? NSNumber)?.intValue,
let animationCurve = UIView.AnimationCurve(rawValue: curveValue)
else {
throw ParseError.missingAnimationCurve
}
self.animationCurve = animationCurve
screen = notification.object as? UIScreen
}
enum ParseError: Error, Equatable {
case missingUserInfo
case missingEndingFrame
case missingAnimationDuration
case missingAnimationCurve
}
}
}
extension KeyboardObserver {
private static let isExtensionContext: Bool = {
// This is our best guess for "is this executable an extension?"
if let _ = Bundle.main.infoDictionary?["NSExtension"] {
return true
} else if Bundle.main.bundlePath.hasSuffix(".appex") {
return true
} else {
return false
}
}()
/// This should be called by a keyboard-observing view on setup, to warn developers if something has gone wrong with
/// keyboard setup.
static func logKeyboardSetupWarningIfNeeded() {
guard !isExtensionContext else {
return
}
if KeyboardObserver.didSetupSharedInstanceDuringAppStartup {
return
}
print(
"""
LISTABLE WARNING: The shared instance of the `KeyboardObserver` was not instantiated \
during app startup. While not fatal, this could result in a list being created \
that does not properly position itself to account for the keyboard, if the list is created \
while the keyboard is already visible.
Please ensure you invoke `ListView.configure(with: application)` before the first `ListView` \
is placed on screen to ensure proper keyboard handling.
"""
)
}
}
extension ListView {
/// This should be called in UIApplicationDelegate.application(_:, didFinishLaunchingWithOption:)
/// It ensures that all ListViews will correctly avoid the keyboard
/// - Note: CocoaPods automatically calls this method
@available(iOSApplicationExtension, unavailable, message: "This cannot be used in application extensions")
@objc(configureWithApplication:)
public static func configure(with application: UIApplication) {
_ = KeyboardObserver.shared
KeyboardObserver.didSetupSharedInstanceDuringAppStartup = true
}
}