MessagesCollectionView.swift 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. /*
  2. MIT License
  3. Copyright (c) 2017-2018 MessageKit
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in all
  11. copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. 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
  18. SOFTWARE.
  19. */
  20. import UIKit
  21. open class MessagesCollectionView: UICollectionView {
  22. // MARK: - Properties
  23. open weak var messagesDataSource: MessagesDataSource?
  24. open weak var messagesDisplayDelegate: MessagesDisplayDelegate?
  25. open weak var messagesLayoutDelegate: MessagesLayoutDelegate?
  26. open weak var messageCellDelegate: MessageCellDelegate?
  27. private var indexPathForLastItem: IndexPath? {
  28. let lastSection = numberOfSections - 1
  29. guard lastSection >= 0, numberOfItems(inSection: lastSection) > 0 else { return nil }
  30. return IndexPath(item: numberOfItems(inSection: lastSection) - 1, section: lastSection)
  31. }
  32. // MARK: - Initializers
  33. public override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
  34. super.init(frame: frame, collectionViewLayout: layout)
  35. backgroundColor = .white
  36. registerReusableViews()
  37. setupGestureRecognizers()
  38. }
  39. required public init?(coder aDecoder: NSCoder) {
  40. fatalError("init(coder:) has not been implemented")
  41. }
  42. public convenience init() {
  43. self.init(frame: .zero, collectionViewLayout: MessagesCollectionViewFlowLayout())
  44. }
  45. // MARK: - Methods
  46. private func registerReusableViews() {
  47. register(TextMessageCell.self)
  48. register(MediaMessageCell.self)
  49. register(LocationMessageCell.self)
  50. register(MessageReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader)
  51. register(MessageReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter)
  52. }
  53. private func setupGestureRecognizers() {
  54. let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture(_:)))
  55. tapGesture.delaysTouchesBegan = true
  56. addGestureRecognizer(tapGesture)
  57. }
  58. @objc
  59. open func handleTapGesture(_ gesture: UIGestureRecognizer) {
  60. guard gesture.state == .ended else { return }
  61. let touchLocation = gesture.location(in: self)
  62. guard let indexPath = indexPathForItem(at: touchLocation) else { return }
  63. let cell = cellForItem(at: indexPath) as? MessageContentCell
  64. cell?.handleTapGesture(gesture)
  65. }
  66. public func scrollToBottom(animated: Bool = false) {
  67. let collectionViewContentHeight = collectionViewLayout.collectionViewContentSize.height
  68. performBatchUpdates(nil) { _ in
  69. self.scrollRectToVisible(CGRect(0.0, collectionViewContentHeight - 1.0, 1.0, 1.0), animated: animated)
  70. }
  71. }
  72. public func reloadDataAndKeepOffset() {
  73. // stop scrolling
  74. setContentOffset(contentOffset, animated: false)
  75. // calculate the offset and reloadData
  76. let beforeContentSize = contentSize
  77. reloadData()
  78. layoutIfNeeded()
  79. let afterContentSize = contentSize
  80. // reset the contentOffset after data is updated
  81. let newOffset = CGPoint(
  82. x: contentOffset.x + (afterContentSize.width - beforeContentSize.width),
  83. y: contentOffset.y + (afterContentSize.height - beforeContentSize.height))
  84. setContentOffset(newOffset, animated: false)
  85. }
  86. /// Registers a particular cell using its reuse-identifier
  87. public func register<T: UICollectionViewCell>(_ cellClass: T.Type) {
  88. register(cellClass, forCellWithReuseIdentifier: String(describing: T.self))
  89. }
  90. /// Registers a reusable view for a specific SectionKind
  91. public func register<T: UICollectionReusableView>(_ headerFooterClass: T.Type, forSupplementaryViewOfKind kind: String) {
  92. register(headerFooterClass,
  93. forSupplementaryViewOfKind: kind,
  94. withReuseIdentifier: String(describing: T.self))
  95. }
  96. /// Generically dequeues a cell of the correct type allowing you to avoid scattering your code with guard-let-else-fatal
  97. public func dequeueReusableCell<T: UICollectionViewCell>(_ cellClass: T.Type, for indexPath: IndexPath) -> T {
  98. guard let cell = dequeueReusableCell(withReuseIdentifier: String(describing: T.self), for: indexPath) as? T else {
  99. fatalError("Unable to dequeue \(String(describing: cellClass)) with reuseId of \(String(describing: T.self))")
  100. }
  101. return cell
  102. }
  103. /// Generically dequeues a header of the correct type allowing you to avoid scattering your code with guard-let-else-fatal
  104. public func dequeueReusableHeaderView<T: UICollectionReusableView>(_ viewClass: T.Type, for indexPath: IndexPath) -> T {
  105. let view = dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: String(describing: T.self), for: indexPath)
  106. guard let viewType = view as? T else {
  107. fatalError("Unable to dequeue \(String(describing: viewClass)) with reuseId of \(String(describing: T.self))")
  108. }
  109. return viewType
  110. }
  111. /// Generically dequeues a footer of the correct type allowing you to avoid scattering your code with guard-let-else-fatal
  112. public func dequeueReusableFooterView<T: UICollectionReusableView>(_ viewClass: T.Type, for indexPath: IndexPath) -> T {
  113. let view = dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: String(describing: T.self), for: indexPath)
  114. guard let viewType = view as? T else {
  115. fatalError("Unable to dequeue \(String(describing: viewClass)) with reuseId of \(String(describing: T.self))")
  116. }
  117. return viewType
  118. }
  119. }