123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295 |
- /*
- 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
- /// 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 scrollsToBottomOnKeybordBeginsEditing: 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
- }
- 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 viewDidLayoutSubviews() {
- // Hack to prevent animation of the contentInset after viewDidAppear
- if isFirstLayout {
- defer { isFirstLayout = false }
- addKeyboardObservers()
- messageCollectionViewBottomInset = keyboardOffsetFrame.height
- }
- adjustScrollViewInset()
- }
- // 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
- }
- 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:
- fatalError(MessageKitError.customDataUnresolvedCell)
- }
- }
- 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()
- }
- }
|