AttachmentManager.swift 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. //
  2. // AttachmentManager.swift
  3. // InputBarAccessoryView
  4. //
  5. // Copyright © 2017-2019 Nathan Tannar.
  6. //
  7. // Permission is hereby granted, free of charge, to any person obtaining a copy
  8. // of this software and associated documentation files (the "Software"), to deal
  9. // in the Software without restriction, including without limitation the rights
  10. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. // copies of the Software, and to permit persons to whom the Software is
  12. // furnished to do so, subject to the following conditions:
  13. //
  14. // The above copyright notice and this permission notice shall be included in all
  15. // copies or substantial portions of the Software.
  16. //
  17. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  23. // SOFTWARE.
  24. //
  25. // Created by Nathan Tannar on 10/4/17.
  26. //
  27. import UIKit
  28. open class AttachmentManager: NSObject, InputPlugin {
  29. public enum Attachment {
  30. case image(UIImage)
  31. case url(URL)
  32. case data(Data)
  33. @available(*, deprecated, message: ".other(AnyObject) has been depricated as of 2.0.0")
  34. case other(AnyObject)
  35. }
  36. // MARK: - Properties [Public]
  37. /// A protocol that can recieve notifications from the `AttachmentManager`
  38. open weak var delegate: AttachmentManagerDelegate?
  39. /// A protocol to passes data to the `AttachmentManager`
  40. open weak var dataSource: AttachmentManagerDataSource?
  41. open lazy var attachmentView: AttachmentCollectionView = { [weak self] in
  42. let attachmentView = AttachmentCollectionView()
  43. attachmentView.dataSource = self
  44. attachmentView.delegate = self
  45. return attachmentView
  46. }()
  47. /// The attachments that the managers holds
  48. private(set) public var attachments = [Attachment]() { didSet { reloadData() } }
  49. /// A flag you can use to determine if you want the manager to be always visible
  50. open var isPersistent = false { didSet { attachmentView.reloadData() } }
  51. /// A flag to determine if the AddAttachmentCell is visible
  52. open var showAddAttachmentCell = true { didSet { attachmentView.reloadData() } }
  53. /// The color applied to the backgroundColor of the deleteButton in each `AttachmentCell`
  54. open var tintColor: UIColor = UIColor(red: 0, green: 0.5, blue: 1, alpha: 1)
  55. // MARK: - Initialization
  56. public override init() {
  57. super.init()
  58. }
  59. // MARK: - InputPlugin
  60. open func reloadData() {
  61. attachmentView.reloadData()
  62. delegate?.attachmentManager(self, didReloadTo: attachments)
  63. delegate?.attachmentManager(self, shouldBecomeVisible: attachments.count > 0 || isPersistent)
  64. }
  65. /// Invalidates the `AttachmentManagers` session by removing all attachments
  66. open func invalidate() {
  67. attachments = []
  68. }
  69. /// Appends the object to the attachments
  70. ///
  71. /// - Parameter object: The object to append
  72. @discardableResult
  73. open func handleInput(of object: AnyObject) -> Bool {
  74. let attachment: Attachment
  75. if let image = object as? UIImage {
  76. attachment = .image(image)
  77. } else if let url = object as? URL {
  78. attachment = .url(url)
  79. } else if let data = object as? Data {
  80. attachment = .data(data)
  81. } else {
  82. return false
  83. }
  84. insertAttachment(attachment, at: attachments.count)
  85. return true
  86. }
  87. // MARK: - API [Public]
  88. /// Performs an animated insertion of an attachment at an index
  89. ///
  90. /// - Parameter index: The index to insert the attachment at
  91. open func insertAttachment(_ attachment: Attachment, at index: Int) {
  92. attachmentView.performBatchUpdates({
  93. self.attachments.insert(attachment, at: index)
  94. self.attachmentView.insertItems(at: [IndexPath(row: index, section: 0)])
  95. }, completion: { success in
  96. self.attachmentView.reloadData()
  97. self.delegate?.attachmentManager(self, didInsert: attachment, at: index)
  98. self.delegate?.attachmentManager(self, shouldBecomeVisible: self.attachments.count > 0 || self.isPersistent)
  99. })
  100. }
  101. /// Performs an animated removal of an attachment at an index
  102. ///
  103. /// - Parameter index: The index to remove the attachment at
  104. open func removeAttachment(at index: Int) {
  105. let attachment = attachments[index]
  106. attachmentView.performBatchUpdates({
  107. self.attachments.remove(at: index)
  108. self.attachmentView.deleteItems(at: [IndexPath(row: index, section: 0)])
  109. }, completion: { success in
  110. self.attachmentView.reloadData()
  111. self.delegate?.attachmentManager(self, didRemove: attachment, at: index)
  112. self.delegate?.attachmentManager(self, shouldBecomeVisible: self.attachments.count > 0 || self.isPersistent)
  113. })
  114. }
  115. }
  116. extension AttachmentManager: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
  117. // MARK: - UICollectionViewDelegate
  118. final public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  119. if indexPath.row == attachments.count {
  120. delegate?.attachmentManager(self, didSelectAddAttachmentAt: indexPath.row)
  121. delegate?.attachmentManager(self, shouldBecomeVisible: attachments.count > 0 || isPersistent)
  122. }
  123. }
  124. // MARK: - UICollectionViewDataSource
  125. final public func numberOfItems(inSection section: Int) -> Int {
  126. return 1
  127. }
  128. final public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  129. return attachments.count + (showAddAttachmentCell ? 1 : 0)
  130. }
  131. final public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  132. if indexPath.row == attachments.count && showAddAttachmentCell {
  133. return createAttachmentCell(in: collectionView, at: indexPath)
  134. }
  135. let attachment = attachments[indexPath.row]
  136. if let cell = dataSource?.attachmentManager(self, cellFor: attachment, at: indexPath.row) {
  137. return cell
  138. } else {
  139. // Only images are supported by default
  140. switch attachment {
  141. case .image(let image):
  142. guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ImageAttachmentCell.reuseIdentifier, for: indexPath) as? ImageAttachmentCell else {
  143. fatalError()
  144. }
  145. cell.attachment = attachment
  146. cell.indexPath = indexPath
  147. cell.manager = self
  148. cell.imageView.image = image
  149. cell.imageView.tintColor = tintColor
  150. cell.deleteButton.backgroundColor = tintColor
  151. return cell
  152. default:
  153. return collectionView.dequeueReusableCell(withReuseIdentifier: AttachmentCell.reuseIdentifier, for: indexPath) as! AttachmentCell
  154. }
  155. }
  156. }
  157. // MARK: - UICollectionViewDelegateFlowLayout
  158. final public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
  159. var height = attachmentView.intrinsicContentHeight
  160. if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
  161. height -= (layout.sectionInset.bottom + layout.sectionInset.top + collectionView.contentInset.top + collectionView.contentInset.bottom)
  162. }
  163. return CGSize(width: height, height: height)
  164. }
  165. open func createAttachmentCell(in collectionView: UICollectionView, at indexPath: IndexPath) -> AttachmentCell {
  166. guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: AttachmentCell.reuseIdentifier, for: indexPath) as? AttachmentCell else {
  167. fatalError()
  168. }
  169. cell.deleteButton.isHidden = true
  170. // Draw a plus
  171. let frame = CGRect(origin: CGPoint(x: cell.bounds.origin.x,
  172. y: cell.bounds.origin.y),
  173. size: CGSize(width: cell.bounds.width - cell.padding.left - cell.padding.right,
  174. height: cell.bounds.height - cell.padding.top - cell.padding.bottom))
  175. let strokeWidth: CGFloat = 3
  176. let length: CGFloat = frame.width / 2
  177. let vLayer = CAShapeLayer()
  178. vLayer.path = UIBezierPath(roundedRect: CGRect(x: frame.midX - (strokeWidth / 2),
  179. y: frame.midY - (length / 2),
  180. width: strokeWidth,
  181. height: length), cornerRadius: 5).cgPath
  182. vLayer.fillColor = UIColor.lightGray.cgColor
  183. let hLayer = CAShapeLayer()
  184. hLayer.path = UIBezierPath(roundedRect: CGRect(x: frame.midX - (length / 2),
  185. y: frame.midY - (strokeWidth / 2),
  186. width: length,
  187. height: strokeWidth), cornerRadius: 5).cgPath
  188. hLayer.fillColor = UIColor.lightGray.cgColor
  189. cell.containerView.layer.addSublayer(vLayer)
  190. cell.containerView.layer.addSublayer(hLayer)
  191. return cell
  192. }
  193. }