MessagesCollectionViewFlowLayout.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. /*
  2. MIT License
  3. Copyright (c) 2017-2019 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. public private(set) var isTypingIndicatorViewHidden: Bool = true
  54. // MARK: - Initializers
  55. public override init() {
  56. super.init()
  57. setupView()
  58. setupObserver()
  59. }
  60. required public init?(coder aDecoder: NSCoder) {
  61. super.init(coder: aDecoder)
  62. setupView()
  63. setupObserver()
  64. }
  65. deinit {
  66. NotificationCenter.default.removeObserver(self)
  67. }
  68. // MARK: - Methods
  69. private func setupView() {
  70. sectionInset = UIEdgeInsets(top: 4, left: 8, bottom: 4, right: 8)
  71. }
  72. private func setupObserver() {
  73. NotificationCenter.default.addObserver(self,
  74. selector: #selector(MessagesCollectionViewFlowLayout.handleOrientationChange(_:)),
  75. name: UIDevice.orientationDidChangeNotification,
  76. object: nil)
  77. }
  78. // MARK: - Typing Indicator API
  79. /// Notifies the layout that the typing indicator will change state
  80. ///
  81. /// - Parameters:
  82. /// - isHidden: A Boolean value that is to be the new state of the typing indicator
  83. internal func setTypingIndicatorViewHidden(_ isHidden: Bool) {
  84. isTypingIndicatorViewHidden = isHidden
  85. }
  86. /// A method that by default checks if the section is the last in the
  87. /// `messagesCollectionView` and that `isTypingIndicatorViewHidden`
  88. /// is FALSE
  89. ///
  90. /// - Parameter section
  91. /// - Returns: A Boolean indicating if the TypingIndicator should be presented at the given section
  92. open func isSectionReservedForTypingIndicator(_ section: Int) -> Bool {
  93. return !isTypingIndicatorViewHidden && section == messagesCollectionView.numberOfSections - 1
  94. }
  95. // MARK: - Attributes
  96. open override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
  97. guard let attributesArray = super.layoutAttributesForElements(in: rect) as? [MessagesCollectionViewLayoutAttributes] else {
  98. return nil
  99. }
  100. for attributes in attributesArray where attributes.representedElementCategory == .cell {
  101. let cellSizeCalculator = cellSizeCalculatorForItem(at: attributes.indexPath)
  102. cellSizeCalculator.configure(attributes: attributes)
  103. }
  104. return attributesArray
  105. }
  106. open override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
  107. guard let attributes = super.layoutAttributesForItem(at: indexPath) as? MessagesCollectionViewLayoutAttributes else {
  108. return nil
  109. }
  110. if attributes.representedElementCategory == .cell {
  111. let cellSizeCalculator = cellSizeCalculatorForItem(at: attributes.indexPath)
  112. cellSizeCalculator.configure(attributes: attributes)
  113. }
  114. return attributes
  115. }
  116. // MARK: - Layout Invalidation
  117. open override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
  118. return collectionView?.bounds.width != newBounds.width
  119. }
  120. open override func invalidationContext(forBoundsChange newBounds: CGRect) -> UICollectionViewLayoutInvalidationContext {
  121. let context = super.invalidationContext(forBoundsChange: newBounds)
  122. guard let flowLayoutContext = context as? UICollectionViewFlowLayoutInvalidationContext else { return context }
  123. flowLayoutContext.invalidateFlowLayoutDelegateMetrics = shouldInvalidateLayout(forBoundsChange: newBounds)
  124. return flowLayoutContext
  125. }
  126. @objc
  127. private func handleOrientationChange(_ notification: Notification) {
  128. invalidateLayout()
  129. }
  130. // MARK: - Cell Sizing
  131. lazy open var textMessageSizeCalculator = TextMessageSizeCalculator(layout: self)
  132. lazy open var attributedTextMessageSizeCalculator = TextMessageSizeCalculator(layout: self)
  133. lazy open var emojiMessageSizeCalculator: TextMessageSizeCalculator = {
  134. let sizeCalculator = TextMessageSizeCalculator(layout: self)
  135. sizeCalculator.messageLabelFont = UIFont.systemFont(ofSize: sizeCalculator.messageLabelFont.pointSize * 2)
  136. return sizeCalculator
  137. }()
  138. lazy open var textMediaMessageSizeCalculator = TextMediaMessageSizeCalculator(layout: self)
  139. lazy open var photoMessageSizeCalculator = MediaMessageSizeCalculator(layout: self)
  140. lazy open var videoMessageSizeCalculator = MediaMessageSizeCalculator(layout: self)
  141. lazy open var locationMessageSizeCalculator = LocationMessageSizeCalculator(layout: self)
  142. lazy open var audioMessageSizeCalculator = AudioMessageSizeCalculator(layout: self)
  143. lazy open var contactMessageSizeCalculator = ContactMessageSizeCalculator(layout: self)
  144. lazy open var typingIndicatorSizeCalculator = TypingCellSizeCalculator(layout: self)
  145. lazy open var customMessageSizeCalculator = TextMessageSizeCalculator(layout: self)
  146. /// Note:
  147. /// - If you override this method, remember to call MessageLayoutDelegate's
  148. /// customCellSizeCalculator(for:at:in:) method for MessageKind.custom messages, if necessary
  149. /// - If you are using the typing indicator be sure to return the `typingIndicatorSizeCalculator`
  150. /// when the section is reserved for it, indicated by `isSectionReservedForTypingIndicator`
  151. open func cellSizeCalculatorForItem(at indexPath: IndexPath) -> CellSizeCalculator {
  152. if isSectionReservedForTypingIndicator(indexPath.section) {
  153. return typingIndicatorSizeCalculator
  154. }
  155. let message = messagesDataSource.messageForItem(at: indexPath, in: messagesCollectionView)
  156. switch message.kind {
  157. case .text:
  158. return textMessageSizeCalculator
  159. case .attributedText:
  160. return attributedTextMessageSizeCalculator
  161. case .emoji:
  162. return emojiMessageSizeCalculator
  163. case .photo:
  164. return photoMessageSizeCalculator
  165. case .photoText, .videoText, .fileText:
  166. return textMediaMessageSizeCalculator
  167. case .video:
  168. return videoMessageSizeCalculator
  169. case .location:
  170. return locationMessageSizeCalculator
  171. case .audio:
  172. return audioMessageSizeCalculator
  173. case .contact:
  174. return contactMessageSizeCalculator
  175. case .info:
  176. return customMessageSizeCalculator
  177. case .custom:
  178. return messagesLayoutDelegate.customCellSizeCalculator(for: message, at: indexPath, in: messagesCollectionView)
  179. }
  180. }
  181. open func sizeForItem(at indexPath: IndexPath) -> CGSize {
  182. let calculator = cellSizeCalculatorForItem(at: indexPath)
  183. return calculator.sizeForItem(at: indexPath)
  184. }
  185. /// Set `incomingAvatarSize` of all `MessageSizeCalculator`s
  186. public func setMessageIncomingAvatarSize(_ newSize: CGSize) {
  187. messageSizeCalculators().forEach { $0.incomingAvatarSize = newSize }
  188. }
  189. /// Set `outgoingAvatarSize` of all `MessageSizeCalculator`s
  190. public func setMessageOutgoingAvatarSize(_ newSize: CGSize) {
  191. messageSizeCalculators().forEach { $0.outgoingAvatarSize = newSize }
  192. }
  193. /// Set `incomingAvatarPosition` of all `MessageSizeCalculator`s
  194. public func setMessageIncomingAvatarPosition(_ newPosition: AvatarPosition) {
  195. messageSizeCalculators().forEach { $0.incomingAvatarPosition = newPosition }
  196. }
  197. /// Set `outgoingAvatarPosition` of all `MessageSizeCalculator`s
  198. public func setMessageOutgoingAvatarPosition(_ newPosition: AvatarPosition) {
  199. messageSizeCalculators().forEach { $0.outgoingAvatarPosition = newPosition }
  200. }
  201. /// Set `avatarLeadingTrailingPadding` of all `MessageSizeCalculator`s
  202. public func setAvatarLeadingTrailingPadding(_ newPadding: CGFloat) {
  203. messageSizeCalculators().forEach { $0.avatarLeadingTrailingPadding = newPadding }
  204. }
  205. /// Set `incomingMessagePadding` of all `MessageSizeCalculator`s
  206. public func setMessageIncomingMessagePadding(_ newPadding: UIEdgeInsets) {
  207. messageSizeCalculators().forEach { $0.incomingMessagePadding = newPadding }
  208. }
  209. /// Set `outgoingMessagePadding` of all `MessageSizeCalculator`s
  210. public func setMessageOutgoingMessagePadding(_ newPadding: UIEdgeInsets) {
  211. messageSizeCalculators().forEach { $0.outgoingMessagePadding = newPadding }
  212. }
  213. /// Set `incomingCellTopLabelAlignment` of all `MessageSizeCalculator`s
  214. public func setMessageIncomingCellTopLabelAlignment(_ newAlignment: LabelAlignment) {
  215. messageSizeCalculators().forEach { $0.incomingCellTopLabelAlignment = newAlignment }
  216. }
  217. /// Set `outgoingCellTopLabelAlignment` of all `MessageSizeCalculator`s
  218. public func setMessageOutgoingCellTopLabelAlignment(_ newAlignment: LabelAlignment) {
  219. messageSizeCalculators().forEach { $0.outgoingCellTopLabelAlignment = newAlignment }
  220. }
  221. /// Set `incomingCellBottomLabelAlignment` of all `MessageSizeCalculator`s
  222. public func setMessageIncomingCellBottomLabelAlignment(_ newAlignment: LabelAlignment) {
  223. messageSizeCalculators().forEach { $0.incomingCellBottomLabelAlignment = newAlignment }
  224. }
  225. /// Set `outgoingCellBottomLabelAlignment` of all `MessageSizeCalculator`s
  226. public func setMessageOutgoingCellBottomLabelAlignment(_ newAlignment: LabelAlignment) {
  227. messageSizeCalculators().forEach { $0.outgoingCellBottomLabelAlignment = newAlignment }
  228. }
  229. /// Set `incomingMessageTopLabelAlignment` of all `MessageSizeCalculator`s
  230. public func setMessageIncomingMessageTopLabelAlignment(_ newAlignment: LabelAlignment) {
  231. messageSizeCalculators().forEach { $0.incomingMessageTopLabelAlignment = newAlignment }
  232. }
  233. /// Set `outgoingMessageTopLabelAlignment` of all `MessageSizeCalculator`s
  234. public func setMessageOutgoingMessageTopLabelAlignment(_ newAlignment: LabelAlignment) {
  235. messageSizeCalculators().forEach { $0.outgoingMessageTopLabelAlignment = newAlignment }
  236. }
  237. /// Set `incomingMessageBottomLabelAlignment` of all `MessageSizeCalculator`s
  238. public func setMessageIncomingMessageBottomLabelAlignment(_ newAlignment: LabelAlignment) {
  239. messageSizeCalculators().forEach { $0.incomingMessageBottomLabelAlignment = newAlignment }
  240. }
  241. /// Set `outgoingMessageBottomLabelAlignment` of all `MessageSizeCalculator`s
  242. public func setMessageOutgoingMessageBottomLabelAlignment(_ newAlignment: LabelAlignment) {
  243. messageSizeCalculators().forEach { $0.outgoingMessageBottomLabelAlignment = newAlignment }
  244. }
  245. /// Set `incomingAccessoryViewSize` of all `MessageSizeCalculator`s
  246. public func setMessageIncomingAccessoryViewSize(_ newSize: CGSize) {
  247. messageSizeCalculators().forEach { $0.incomingAccessoryViewSize = newSize }
  248. }
  249. /// Set `outgoingAccessoryViewSize` of all `MessageSizeCalculator`s
  250. public func setMessageOutgoingAccessoryViewSize(_ newSize: CGSize) {
  251. messageSizeCalculators().forEach { $0.outgoingAccessoryViewSize = newSize }
  252. }
  253. /// Set `incomingAccessoryViewPadding` of all `MessageSizeCalculator`s
  254. public func setMessageIncomingAccessoryViewPadding(_ newPadding: HorizontalEdgeInsets) {
  255. messageSizeCalculators().forEach { $0.incomingAccessoryViewPadding = newPadding }
  256. }
  257. /// Set `outgoingAccessoryViewPadding` of all `MessageSizeCalculator`s
  258. public func setMessageOutgoingAccessoryViewPadding(_ newPadding: HorizontalEdgeInsets) {
  259. messageSizeCalculators().forEach { $0.outgoingAccessoryViewPadding = newPadding }
  260. }
  261. /// Set `incomingAccessoryViewPosition` of all `MessageSizeCalculator`s
  262. public func setMessageIncomingAccessoryViewPosition(_ newPosition: AccessoryPosition) {
  263. messageSizeCalculators().forEach { $0.incomingAccessoryViewPosition = newPosition }
  264. }
  265. /// Set `outgoingAccessoryViewPosition` of all `MessageSizeCalculator`s
  266. public func setMessageOutgoingAccessoryViewPosition(_ newPosition: AccessoryPosition) {
  267. messageSizeCalculators().forEach { $0.outgoingAccessoryViewPosition = newPosition }
  268. }
  269. /// Get all `MessageSizeCalculator`s
  270. open func messageSizeCalculators() -> [MessageSizeCalculator] {
  271. return [textMessageSizeCalculator,
  272. attributedTextMessageSizeCalculator,
  273. emojiMessageSizeCalculator,
  274. textMediaMessageSizeCalculator,
  275. photoMessageSizeCalculator,
  276. videoMessageSizeCalculator,
  277. locationMessageSizeCalculator,
  278. audioMessageSizeCalculator,
  279. contactMessageSizeCalculator
  280. ]
  281. }
  282. }