InputTextView.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  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. /**
  22. A `UITextView` that has a `UILabel` embedded for placeholder text
  23. ## Important Notes ##
  24. 1. Changing the font, textAlignment or textContainerInset automatically performs the same modifications to the placeholderLabel
  25. 2. Intended to be used in an `MessageInputBar`
  26. 3. Default placeholder text is "New Message"
  27. 4. Will pass a pasted image it's `MessageInputBar`'s `InputManager`s
  28. */
  29. open class InputTextView: UITextView {
  30. // MARK: - Properties
  31. open override var text: String! {
  32. didSet {
  33. postTextViewDidChangeNotification()
  34. }
  35. }
  36. open override var attributedText: NSAttributedString! {
  37. didSet {
  38. postTextViewDidChangeNotification()
  39. }
  40. }
  41. /// The images that are currently stored as `NSTextAttachment`'s
  42. open var images: [UIImage] {
  43. return parseForAttachedImages()
  44. }
  45. open var components: [Any] {
  46. return parseForComponents()
  47. }
  48. open var isImagePasteEnabled: Bool = true
  49. /// A UILabel that holds the `InputTextView`'s placeholder text
  50. public let placeholderLabel: UILabel = {
  51. let label = UILabel()
  52. label.numberOfLines = 0
  53. label.textColor = .lightGray
  54. label.text = "New Message"
  55. label.backgroundColor = .clear
  56. label.translatesAutoresizingMaskIntoConstraints = false
  57. return label
  58. }()
  59. /// The placeholder text that appears when there is no text. The default value is "New Message"
  60. open var placeholder: String? = "New Message" {
  61. didSet {
  62. placeholderLabel.text = placeholder
  63. }
  64. }
  65. /// The placeholderLabel's textColor
  66. open var placeholderTextColor: UIColor? = .lightGray {
  67. didSet {
  68. placeholderLabel.textColor = placeholderTextColor
  69. }
  70. }
  71. /// The `UIEdgeInsets` the placeholderLabel has within the `InputTextView`
  72. open var placeholderLabelInsets: UIEdgeInsets = UIEdgeInsets(top: 8, left: 4, bottom: 8, right: 4) {
  73. didSet {
  74. updateConstraintsForPlaceholderLabel()
  75. }
  76. }
  77. /// The font of the `InputTextView`. When set the placeholderLabel's font is also updated
  78. open override var font: UIFont! {
  79. didSet {
  80. placeholderLabel.font = font
  81. }
  82. }
  83. /// The `textAlignment` of the `InputTextView`. When set the placeholderLabel's `textAlignment` is also updated
  84. open override var textAlignment: NSTextAlignment {
  85. didSet {
  86. placeholderLabel.textAlignment = textAlignment
  87. }
  88. }
  89. /// The textContainerInset of the `InputTextView`. When set the placeholderLabelInsets is also updated
  90. open override var textContainerInset: UIEdgeInsets {
  91. didSet {
  92. placeholderLabelInsets = textContainerInset
  93. }
  94. }
  95. open override var scrollIndicatorInsets: UIEdgeInsets {
  96. didSet {
  97. // When .zero a rendering issue can occur
  98. if scrollIndicatorInsets == .zero {
  99. scrollIndicatorInsets = UIEdgeInsets(top: .leastNonzeroMagnitude,
  100. left: .leastNonzeroMagnitude,
  101. bottom: .leastNonzeroMagnitude,
  102. right: .leastNonzeroMagnitude)
  103. }
  104. }
  105. }
  106. /// A weak reference to the `MessageInputBar` that the `InputTextView` is contained within
  107. open weak var messageInputBar: MessageInputBar?
  108. /// The constraints of the placeholderLabel
  109. private var placeholderLabelConstraintSet: NSLayoutConstraintSet?
  110. // MARK: - Initializers
  111. public convenience init() {
  112. self.init(frame: .zero)
  113. }
  114. public override init(frame: CGRect, textContainer: NSTextContainer?) {
  115. super.init(frame: frame, textContainer: textContainer)
  116. setup()
  117. }
  118. required public init?(coder aDecoder: NSCoder) {
  119. super.init(coder: aDecoder)
  120. setup()
  121. }
  122. deinit {
  123. NotificationCenter.default.removeObserver(self)
  124. }
  125. // MARK: - Setup
  126. /// Sets up the default properties
  127. open func setup() {
  128. backgroundColor = .clear
  129. font = UIFont.preferredFont(forTextStyle: .body)
  130. isScrollEnabled = false
  131. scrollIndicatorInsets = UIEdgeInsets(top: .leastNonzeroMagnitude,
  132. left: .leastNonzeroMagnitude,
  133. bottom: .leastNonzeroMagnitude,
  134. right: .leastNonzeroMagnitude)
  135. setupPlaceholderLabel()
  136. setupObservers()
  137. }
  138. /// Adds the placeholderLabel to the view and sets up its initial constraints
  139. private func setupPlaceholderLabel() {
  140. addSubview(placeholderLabel)
  141. placeholderLabelConstraintSet = NSLayoutConstraintSet(
  142. top: placeholderLabel.topAnchor.constraint(equalTo: topAnchor, constant: placeholderLabelInsets.top),
  143. bottom: placeholderLabel.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -placeholderLabelInsets.bottom),
  144. left: placeholderLabel.leftAnchor.constraint(equalTo: leftAnchor, constant: placeholderLabelInsets.left),
  145. right: placeholderLabel.rightAnchor.constraint(equalTo: rightAnchor, constant: -placeholderLabelInsets.right),
  146. centerX: placeholderLabel.centerXAnchor.constraint(equalTo: centerXAnchor),
  147. centerY: placeholderLabel.centerYAnchor.constraint(equalTo: centerYAnchor)
  148. )
  149. placeholderLabelConstraintSet?.centerX?.priority = .defaultLow
  150. placeholderLabelConstraintSet?.centerY?.priority = .defaultLow
  151. placeholderLabelConstraintSet?.activate()
  152. }
  153. /// Adds the required notification observers
  154. private func setupObservers() {
  155. NotificationCenter.default.addObserver(self,
  156. selector: #selector(InputTextView.redrawTextAttachments),
  157. name: UIDevice.orientationDidChangeNotification, object: nil)
  158. NotificationCenter.default.addObserver(self,
  159. selector: #selector(InputTextView.textViewTextDidChange),
  160. name: UITextView.textDidChangeNotification, object: nil)
  161. }
  162. /// Updates the placeholderLabels constraint constants to match the placeholderLabelInsets
  163. private func updateConstraintsForPlaceholderLabel() {
  164. placeholderLabelConstraintSet?.top?.constant = placeholderLabelInsets.top
  165. placeholderLabelConstraintSet?.bottom?.constant = -placeholderLabelInsets.bottom
  166. placeholderLabelConstraintSet?.left?.constant = placeholderLabelInsets.left
  167. placeholderLabelConstraintSet?.right?.constant = -placeholderLabelInsets.right
  168. }
  169. // MARK: - Notification
  170. private func postTextViewDidChangeNotification() {
  171. NotificationCenter.default.post(name: UITextView.textDidChangeNotification, object: self)
  172. }
  173. @objc
  174. private func textViewTextDidChange() {
  175. placeholderLabel.isHidden = !text.isEmpty
  176. }
  177. // MARK: - Image Paste Support
  178. open override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
  179. if action == NSSelectorFromString("paste:") && UIPasteboard.general.image != nil {
  180. return isImagePasteEnabled
  181. }
  182. return super.canPerformAction(action, withSender: sender)
  183. }
  184. open override func paste(_ sender: Any?) {
  185. guard let image = UIPasteboard.general.image else {
  186. return super.paste(sender)
  187. }
  188. if isImagePasteEnabled {
  189. pasteImageInTextContainer(with: image)
  190. } else {
  191. for plugin in messageInputBar?.plugins ?? [] {
  192. if plugin.handleInput(of: image) {
  193. return
  194. }
  195. }
  196. }
  197. }
  198. /// Addes a new UIImage to the NSTextContainer as an NSTextAttachment
  199. ///
  200. /// - Parameter image: The image to add
  201. private func pasteImageInTextContainer(with image: UIImage) {
  202. // Add the new image as an NSTextAttachment
  203. let attributedImageString = NSAttributedString(attachment: textAttachment(using: image))
  204. let isEmpty = attributedText.length == 0
  205. // Add a new line character before the image, this is what iMessage does
  206. let newAttributedStingComponent = isEmpty ? NSMutableAttributedString(string: "") : NSMutableAttributedString(string: "\n")
  207. newAttributedStingComponent.append(attributedImageString)
  208. // Add a new line character after the image, this is what iMessage does
  209. newAttributedStingComponent.append(NSAttributedString(string: "\n"))
  210. // The attributes that should be applied to the new NSAttributedString to match the current attributes
  211. let attributes: [NSAttributedString.Key: Any] = [
  212. NSAttributedString.Key.font: font ?? UIFont.preferredFont(forTextStyle: .body),
  213. NSAttributedString.Key.foregroundColor: textColor ?? .black
  214. ]
  215. newAttributedStingComponent.addAttributes(attributes, range: NSRange(location: 0, length: newAttributedStingComponent.length))
  216. textStorage.beginEditing()
  217. // Paste over selected text
  218. textStorage.replaceCharacters(in: selectedRange, with: newAttributedStingComponent)
  219. textStorage.endEditing()
  220. // Advance the range to the selected range plus the number of characters added
  221. let location = selectedRange.location + (isEmpty ? 2 : 3)
  222. selectedRange = NSRange(location: location, length: 0)
  223. // Broadcast a notification to recievers such as the MessageInputBar which will handle resizing
  224. postTextViewDidChangeNotification()
  225. }
  226. /// Returns an NSTextAttachment the provided image that will fit inside the NSTextContainer
  227. ///
  228. /// - Parameter image: The image to create an attachment with
  229. /// - Returns: The formatted NSTextAttachment
  230. private func textAttachment(using image: UIImage) -> NSTextAttachment {
  231. guard let cgImage = image.cgImage else { return NSTextAttachment() }
  232. let scale = image.size.width / (frame.width - 2 * (textContainerInset.left + textContainerInset.right))
  233. let textAttachment = NSTextAttachment()
  234. textAttachment.image = UIImage(cgImage: cgImage, scale: scale, orientation: .up)
  235. return textAttachment
  236. }
  237. /// Returns all images that exist as NSTextAttachment's
  238. ///
  239. /// - Returns: An array of type UIImage
  240. private func parseForAttachedImages() -> [UIImage] {
  241. var images = [UIImage]()
  242. let range = NSRange(location: 0, length: attributedText.length)
  243. attributedText.enumerateAttribute(.attachment, in: range, options: [], using: { value, range, _ -> Void in
  244. if let attachment = value as? NSTextAttachment {
  245. if let image = attachment.image {
  246. images.append(image)
  247. } else if let image = attachment.image(forBounds: attachment.bounds,
  248. textContainer: nil,
  249. characterIndex: range.location) {
  250. images.append(image)
  251. }
  252. }
  253. })
  254. return images
  255. }
  256. /// Returns an array of components (either a String or UIImage) that makes up the textContainer in
  257. /// the order that they were typed
  258. ///
  259. /// - Returns: An array of objects guaranteed to be of UIImage or String
  260. private func parseForComponents() -> [Any] {
  261. var components = [Any]()
  262. var attachments = [(NSRange, UIImage)]()
  263. let length = attributedText.length
  264. let range = NSRange(location: 0, length: length)
  265. attributedText.enumerateAttribute(.attachment, in: range) { (object, range, _) in
  266. if let attachment = object as? NSTextAttachment {
  267. if let image = attachment.image {
  268. attachments.append((range, image))
  269. } else if let image = attachment.image(forBounds: attachment.bounds,
  270. textContainer: nil,
  271. characterIndex: range.location) {
  272. attachments.append((range,image))
  273. }
  274. }
  275. }
  276. var curLocation = 0
  277. if attachments.count == 0 {
  278. let text = attributedText.string.trimmingCharacters(in: .whitespacesAndNewlines)
  279. if !text.isEmpty {
  280. components.append(text)
  281. }
  282. }
  283. else {
  284. attachments.forEach { (attachment) in
  285. let (range, image) = attachment
  286. if curLocation < range.location {
  287. let textRange = NSMakeRange(curLocation, range.location)
  288. let text = attributedText.attributedSubstring(from: textRange).string.trimmingCharacters(in: .whitespacesAndNewlines)
  289. if !text.isEmpty {
  290. components.append(text)
  291. }
  292. }
  293. curLocation = range.location + range.length
  294. components.append(image)
  295. }
  296. if curLocation < length - 1 {
  297. let text = attributedText.attributedSubstring(from: NSMakeRange(curLocation, length - curLocation)).string.trimmingCharacters(in: .whitespacesAndNewlines)
  298. if !text.isEmpty {
  299. components.append(text)
  300. }
  301. }
  302. }
  303. return components
  304. }
  305. /// Redraws the NSTextAttachments in the NSTextContainer to fit the current bounds
  306. @objc
  307. private func redrawTextAttachments() {
  308. guard images.count > 0 else { return }
  309. let range = NSRange(location: 0, length: attributedText.length)
  310. attributedText.enumerateAttribute(.attachment, in: range, options: [], using: { value, _, _ -> Void in
  311. if let attachment = value as? NSTextAttachment, let image = attachment.image {
  312. // Calculates a new width/height ratio to fit the image in the current frame
  313. let newWidth = frame.width - 2 * (textContainerInset.left + textContainerInset.right)
  314. let ratio = image.size.height / image.size.width
  315. attachment.bounds.size = CGSize(width: newWidth, height: ratio * newWidth)
  316. }
  317. })
  318. layoutManager.invalidateLayout(forCharacterRange: range, actualCharacterRange: nil)
  319. }
  320. }