MessagesCollectionViewFlowLayout.swift 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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. import AVFoundation
  22. /// The layout object used by `MessagesCollectionView` to determine the size of all
  23. /// framework provided `MessageCollectionViewCell` subclasses.
  24. open class MessagesCollectionViewFlowLayout: UICollectionViewFlowLayout {
  25. open override class var layoutAttributesClass: AnyClass {
  26. return MessagesCollectionViewLayoutAttributes.self
  27. }
  28. /// The `MessagesCollectionView` that owns this layout object.
  29. public var messagesCollectionView: MessagesCollectionView {
  30. guard let messagesCollectionView = collectionView as? MessagesCollectionView else {
  31. fatalError(MessageKitError.layoutUsedOnForeignType)
  32. }
  33. return messagesCollectionView
  34. }
  35. /// The `MessagesDataSource` for the layout's collection view.
  36. public var messagesDataSource: MessagesDataSource {
  37. guard let messagesDataSource = messagesCollectionView.messagesDataSource else {
  38. fatalError(MessageKitError.nilMessagesDataSource)
  39. }
  40. return messagesDataSource
  41. }
  42. /// The `MessagesLayoutDelegate` for the layout's collection view.
  43. public var messagesLayoutDelegate: MessagesLayoutDelegate {
  44. guard let messagesLayoutDelegate = messagesCollectionView.messagesLayoutDelegate else {
  45. fatalError(MessageKitError.nilMessagesLayoutDelegate)
  46. }
  47. return messagesLayoutDelegate
  48. }
  49. public var itemWidth: CGFloat {
  50. guard let collectionView = collectionView else { return 0 }
  51. return collectionView.frame.width - sectionInset.left - sectionInset.right
  52. }
  53. // MARK: - Initializers
  54. public override init() {
  55. super.init()
  56. sectionInset = UIEdgeInsets(top: 4, left: 8, bottom: 4, right: 8)
  57. NotificationCenter.default.addObserver(self, selector: #selector(MessagesCollectionViewFlowLayout.handleOrientationChange(_:)), name: UIDevice.orientationDidChangeNotification, object: nil)
  58. }
  59. required public init?(coder aDecoder: NSCoder) {
  60. fatalError("init(coder:) has not been implemented")
  61. }
  62. deinit {
  63. NotificationCenter.default.removeObserver(self)
  64. }
  65. // MARK: - Attributes
  66. open override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
  67. guard let attributesArray = super.layoutAttributesForElements(in: rect) as? [MessagesCollectionViewLayoutAttributes] else {
  68. return nil
  69. }
  70. for attributes in attributesArray where attributes.representedElementCategory == .cell {
  71. let cellSizeCalculator = cellSizeCalculatorForItem(at: attributes.indexPath)
  72. cellSizeCalculator.configure(attributes: attributes)
  73. }
  74. return attributesArray
  75. }
  76. open override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
  77. guard let attributes = super.layoutAttributesForItem(at: indexPath) as? MessagesCollectionViewLayoutAttributes else {
  78. return nil
  79. }
  80. if attributes.representedElementCategory == .cell {
  81. let cellSizeCalculator = cellSizeCalculatorForItem(at: attributes.indexPath)
  82. cellSizeCalculator.configure(attributes: attributes)
  83. }
  84. return attributes
  85. }
  86. // MARK: - Layout Invalidation
  87. open override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
  88. return collectionView?.bounds.width != newBounds.width
  89. }
  90. open override func invalidationContext(forBoundsChange newBounds: CGRect) -> UICollectionViewLayoutInvalidationContext {
  91. let context = super.invalidationContext(forBoundsChange: newBounds)
  92. guard let flowLayoutContext = context as? UICollectionViewFlowLayoutInvalidationContext else { return context }
  93. flowLayoutContext.invalidateFlowLayoutDelegateMetrics = shouldInvalidateLayout(forBoundsChange: newBounds)
  94. return flowLayoutContext
  95. }
  96. @objc
  97. private func handleOrientationChange(_ notification: Notification) {
  98. invalidateLayout()
  99. }
  100. // MARK: - Cell Sizing
  101. lazy open var textMessageSizeCalculator = TextMessageSizeCalculator(layout: self)
  102. lazy open var attributedTextMessageSizeCalculator = TextMessageSizeCalculator(layout: self)
  103. lazy open var emojiMessageSizeCalculator = TextMessageSizeCalculator(layout: self)
  104. lazy open var photoMessageSizeCalculator = MediaMessageSizeCalculator(layout: self)
  105. lazy open var videoMessageSizeCalculator = MediaMessageSizeCalculator(layout: self)
  106. lazy open var locationMessageSizeCalculator = LocationMessageSizeCalculator(layout: self)
  107. open func cellSizeCalculatorForItem(at indexPath: IndexPath) -> CellSizeCalculator {
  108. let message = messagesDataSource.messageForItem(at: indexPath, in: messagesCollectionView)
  109. switch message.kind {
  110. case .text:
  111. return textMessageSizeCalculator
  112. case .attributedText:
  113. return attributedTextMessageSizeCalculator
  114. case .emoji:
  115. return emojiMessageSizeCalculator
  116. case .photo:
  117. return photoMessageSizeCalculator
  118. case .video:
  119. return videoMessageSizeCalculator
  120. case .location:
  121. return locationMessageSizeCalculator
  122. case .custom:
  123. fatalError("Must return a CellSizeCalculator for MessageKind.custom(Any?)")
  124. }
  125. }
  126. open func sizeForItem(at indexPath: IndexPath) -> CGSize {
  127. let calculator = cellSizeCalculatorForItem(at: indexPath)
  128. return calculator.sizeForItem(at: indexPath)
  129. }
  130. /// Set `incomingAvatarSize` of all `MessageSizeCalculator`s
  131. public func setMessageIncomingAvatarSize(_ newSize: CGSize) {
  132. messageSizeCalculators().forEach { $0.incomingAvatarSize = newSize }
  133. }
  134. /// Set `outgoingAvatarSize` of all `MessageSizeCalculator`s
  135. public func setMessageOutgoingAvatarSize(_ newSize: CGSize) {
  136. messageSizeCalculators().forEach { $0.outgoingAvatarSize = newSize }
  137. }
  138. /// Set `incomingAvatarPosition` of all `MessageSizeCalculator`s
  139. public func setMessageIncomingAvatarPosition(_ newPosition: AvatarPosition) {
  140. messageSizeCalculators().forEach { $0.incomingAvatarPosition = newPosition }
  141. }
  142. /// Set `outgoingAvatarPosition` of all `MessageSizeCalculator`s
  143. public func setMessageOutgoingAvatarPosition(_ newPosition: AvatarPosition) {
  144. messageSizeCalculators().forEach { $0.outgoingAvatarPosition = newPosition }
  145. }
  146. /// Set `incomingMessagePadding` of all `MessageSizeCalculator`s
  147. public func setMessageIncomingMessagePadding(_ newPadding: UIEdgeInsets) {
  148. messageSizeCalculators().forEach { $0.incomingMessagePadding = newPadding }
  149. }
  150. /// Set `outgoingMessagePadding` of all `MessageSizeCalculator`s
  151. public func setMessageOutgoingMessagePadding(_ newPadding: UIEdgeInsets) {
  152. messageSizeCalculators().forEach { $0.outgoingMessagePadding = newPadding }
  153. }
  154. /// Set `incomingCellTopLabelAlignment` of all `MessageSizeCalculator`s
  155. public func setMessageIncomingCellTopLabelAlignment(_ newAlignment: LabelAlignment) {
  156. messageSizeCalculators().forEach { $0.incomingCellTopLabelAlignment = newAlignment }
  157. }
  158. /// Set `outgoingCellTopLabelAlignment` of all `MessageSizeCalculator`s
  159. public func setMessageOutgoingCellTopLabelAlignment(_ newAlignment: LabelAlignment) {
  160. messageSizeCalculators().forEach { $0.outgoingCellTopLabelAlignment = newAlignment }
  161. }
  162. /// Set `incomingMessageTopLabelAlignment` of all `MessageSizeCalculator`s
  163. public func setMessageIncomingMessageTopLabelAlignment(_ newAlignment: LabelAlignment) {
  164. messageSizeCalculators().forEach { $0.incomingMessageTopLabelAlignment = newAlignment }
  165. }
  166. /// Set `outgoingMessageTopLabelAlignment` of all `MessageSizeCalculator`s
  167. public func setMessageOutgoingMessageTopLabelAlignment(_ newAlignment: LabelAlignment) {
  168. messageSizeCalculators().forEach { $0.outgoingMessageTopLabelAlignment = newAlignment }
  169. }
  170. /// Set `incomingMessageBottomLabelAlignment` of all `MessageSizeCalculator`s
  171. public func setMessageIncomingMessageBottomLabelAlignment(_ newAlignment: LabelAlignment) {
  172. messageSizeCalculators().forEach { $0.incomingMessageBottomLabelAlignment = newAlignment }
  173. }
  174. /// Set `outgoingMessageBottomLabelAlignment` of all `MessageSizeCalculator`s
  175. public func setMessageOutgoingMessageBottomLabelAlignment(_ newAlignment: LabelAlignment) {
  176. messageSizeCalculators().forEach { $0.outgoingMessageBottomLabelAlignment = newAlignment }
  177. }
  178. /// Get all `MessageSizeCalculator`s
  179. open func messageSizeCalculators() -> [MessageSizeCalculator] {
  180. return [textMessageSizeCalculator, attributedTextMessageSizeCalculator, emojiMessageSizeCalculator, photoMessageSizeCalculator, videoMessageSizeCalculator, locationMessageSizeCalculator]
  181. }
  182. }