forked from MessageKit/MessageKit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMessagesViewController.swift
314 lines (256 loc) · 13.2 KB
/
MessagesViewController.swift
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
/*
MIT License
Copyright (c) 2017-2018 MessageKit
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.
*/
import UIKit
import MessageInputBar
/// A subclass of `UIViewController` with a `MessagesCollectionView` object
/// that is used to display conversation interfaces.
open class MessagesViewController: UIViewController,
UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
/// The `MessagesCollectionView` managed by the messages view controller object.
open var messagesCollectionView = MessagesCollectionView()
/// The `MessageInputBar` used as the `inputAccessoryView` in the view controller.
open var messageInputBar = MessageInputBar()
/// A Boolean value that determines whether the `MessagesCollectionView` scrolls to the
/// bottom whenever the `InputTextView` begins editing.
///
/// The default value of this property is `false`.
open var scrollsToBottomOnKeyboardBeginsEditing: Bool = false
/// A Boolean value that determines whether the `MessagesCollectionView`
/// maintains it's current position when the height of the `MessageInputBar` changes.
///
/// The default value of this property is `false`.
open var maintainPositionOnKeyboardFrameChanged: Bool = false
open override var canBecomeFirstResponder: Bool {
return true
}
open override var inputAccessoryView: UIView? {
return messageInputBar
}
open override var shouldAutorotate: Bool {
return false
}
/// A CGFloat value that adds to (or, if negative, subtracts from) the automatically
/// computed value of `messagesCollectionView.contentInset.bottom`. Meant to be used
/// as a measure of last resort when the built-in algorithm does not produce the right
/// value for your app. Please let us know when you end up having to use this property.
open var additionalBottomInset: CGFloat = 0 {
didSet {
let delta = additionalBottomInset - oldValue
messageCollectionViewBottomInset += delta
}
}
private var isFirstLayout: Bool = true
internal var isMessagesControllerBeingDismissed: Bool = false
internal var selectedIndexPathForMenu: IndexPath?
internal var messageCollectionViewBottomInset: CGFloat = 0 {
didSet {
messagesCollectionView.contentInset.bottom = messageCollectionViewBottomInset
messagesCollectionView.scrollIndicatorInsets.bottom = messageCollectionViewBottomInset
}
}
// MARK: - View Life Cycle
open override func viewDidLoad() {
super.viewDidLoad()
setupDefaults()
setupSubviews()
setupConstraints()
setupDelegates()
addMenuControllerObservers()
addObservers()
}
open override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
isMessagesControllerBeingDismissed = false
}
open override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
isMessagesControllerBeingDismissed = true
}
open override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
isMessagesControllerBeingDismissed = false
}
open override func viewDidLayoutSubviews() {
// Hack to prevent animation of the contentInset after viewDidAppear
if isFirstLayout {
defer { isFirstLayout = false }
addKeyboardObservers()
messageCollectionViewBottomInset = requiredInitialScrollViewBottomInset()
}
adjustScrollViewTopInset()
}
// MARK: - Initializers
deinit {
removeKeyboardObservers()
removeMenuControllerObservers()
removeObservers()
clearMemoryCache()
}
// MARK: - Methods [Private]
private func setupDefaults() {
extendedLayoutIncludesOpaqueBars = true
automaticallyAdjustsScrollViewInsets = false
view.backgroundColor = .white
messagesCollectionView.keyboardDismissMode = .interactive
messagesCollectionView.alwaysBounceVertical = true
}
private func setupDelegates() {
messagesCollectionView.delegate = self
messagesCollectionView.dataSource = self
}
private func setupSubviews() {
view.addSubview(messagesCollectionView)
}
private func setupConstraints() {
messagesCollectionView.translatesAutoresizingMaskIntoConstraints = false
let top = messagesCollectionView.topAnchor.constraint(equalTo: view.topAnchor, constant: topLayoutGuide.length)
let bottom = messagesCollectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
if #available(iOS 11.0, *) {
let leading = messagesCollectionView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor)
let trailing = messagesCollectionView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor)
NSLayoutConstraint.activate([top, bottom, trailing, leading])
} else {
let leading = messagesCollectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor)
let trailing = messagesCollectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
NSLayoutConstraint.activate([top, bottom, trailing, leading])
}
}
// MARK: - UICollectionViewDataSource
open func numberOfSections(in collectionView: UICollectionView) -> Int {
guard let collectionView = collectionView as? MessagesCollectionView else {
fatalError(MessageKitError.notMessagesCollectionView)
}
return collectionView.messagesDataSource?.numberOfSections(in: collectionView) ?? 0
}
open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
guard let collectionView = collectionView as? MessagesCollectionView else {
fatalError(MessageKitError.notMessagesCollectionView)
}
return collectionView.messagesDataSource?.numberOfItems(inSection: section, in: collectionView) ?? 0
}
/// Note:
/// If you override this method, remember to call MessagesDataSource's customCell(for:at:in:) for MessageKind.custom messages, if necessary
open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let messagesCollectionView = collectionView as? MessagesCollectionView else {
fatalError(MessageKitError.notMessagesCollectionView)
}
guard let messagesDataSource = messagesCollectionView.messagesDataSource else {
fatalError(MessageKitError.nilMessagesDataSource)
}
let message = messagesDataSource.messageForItem(at: indexPath, in: messagesCollectionView)
switch message.kind {
case .text, .attributedText, .emoji:
let cell = messagesCollectionView.dequeueReusableCell(TextMessageCell.self, for: indexPath)
cell.configure(with: message, at: indexPath, and: messagesCollectionView)
return cell
case .photo, .video:
let cell = messagesCollectionView.dequeueReusableCell(MediaMessageCell.self, for: indexPath)
cell.configure(with: message, at: indexPath, and: messagesCollectionView)
return cell
case .location:
let cell = messagesCollectionView.dequeueReusableCell(LocationMessageCell.self, for: indexPath)
cell.configure(with: message, at: indexPath, and: messagesCollectionView)
return cell
case .custom:
return messagesDataSource.customCell(for: message, at: indexPath, in: messagesCollectionView)
}
}
open func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
guard let messagesCollectionView = collectionView as? MessagesCollectionView else {
fatalError(MessageKitError.notMessagesCollectionView)
}
guard let displayDelegate = messagesCollectionView.messagesDisplayDelegate else {
fatalError(MessageKitError.nilMessagesDisplayDelegate)
}
switch kind {
case UICollectionView.elementKindSectionHeader:
return displayDelegate.messageHeaderView(for: indexPath, in: messagesCollectionView)
case UICollectionView.elementKindSectionFooter:
return displayDelegate.messageFooterView(for: indexPath, in: messagesCollectionView)
default:
fatalError(MessageKitError.unrecognizedSectionKind)
}
}
// MARK: - UICollectionViewDelegateFlowLayout
open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
guard let messagesFlowLayout = collectionViewLayout as? MessagesCollectionViewFlowLayout else { return .zero }
return messagesFlowLayout.sizeForItem(at: indexPath)
}
open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
guard let messagesCollectionView = collectionView as? MessagesCollectionView else {
fatalError(MessageKitError.notMessagesCollectionView)
}
guard let layoutDelegate = messagesCollectionView.messagesLayoutDelegate else {
fatalError(MessageKitError.nilMessagesLayoutDelegate)
}
return layoutDelegate.headerViewSize(for: section, in: messagesCollectionView)
}
open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
guard let messagesCollectionView = collectionView as? MessagesCollectionView else {
fatalError(MessageKitError.notMessagesCollectionView)
}
guard let layoutDelegate = messagesCollectionView.messagesLayoutDelegate else {
fatalError(MessageKitError.nilMessagesLayoutDelegate)
}
return layoutDelegate.footerViewSize(for: section, in: messagesCollectionView)
}
open func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool {
guard let messagesDataSource = messagesCollectionView.messagesDataSource else { return false }
let message = messagesDataSource.messageForItem(at: indexPath, in: messagesCollectionView)
switch message.kind {
case .text, .attributedText, .emoji, .photo:
selectedIndexPathForMenu = indexPath
return true
default:
return false
}
}
open func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
return (action == NSSelectorFromString("copy:"))
}
open func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) {
guard let messagesDataSource = messagesCollectionView.messagesDataSource else {
fatalError(MessageKitError.nilMessagesDataSource)
}
let pasteBoard = UIPasteboard.general
let message = messagesDataSource.messageForItem(at: indexPath, in: messagesCollectionView)
switch message.kind {
case .text(let text), .emoji(let text):
pasteBoard.string = text
case .attributedText(let attributedText):
pasteBoard.string = attributedText.string
case .photo(let mediaItem):
pasteBoard.image = mediaItem.image ?? mediaItem.placeholderImage
default:
break
}
}
// MARK: - Helpers
private func addObservers() {
NotificationCenter.default.addObserver(
self, selector: #selector(clearMemoryCache), name: UIApplication.didReceiveMemoryWarningNotification, object: nil)
}
private func removeObservers() {
NotificationCenter.default.removeObserver(self, name: UIApplication.didReceiveMemoryWarningNotification, object: nil)
}
@objc private func clearMemoryCache() {
MessageStyle.bubbleImageCache.removeAllObjects()
}
}