NSMutableAttributedStringExtension.swift 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. //
  2. // NSMutableAttributedStringExtension.swift
  3. // RichTextView
  4. //
  5. // Created by Ahmed Elkady on 2018-11-20.
  6. // Copyright © 2018 Top Hat. All rights reserved.
  7. //
  8. import UIKit
  9. extension NSAttributedString.Key {
  10. static let customLink = NSAttributedString.Key(rawValue: "customLink")
  11. static let highlight = NSAttributedString.Key(rawValue: "highlight")
  12. }
  13. extension NSMutableAttributedString {
  14. func replaceFont(with newFont: UIFont) {
  15. self.beginEditing()
  16. let defaultFontSize = UIFont.smallSystemFontSize
  17. self.enumerateAttribute(.font, in: NSRange(location: 0, length: self.length)) { (value, range, _) in
  18. guard let oldFont = value as? UIFont,
  19. let newFontDescriptor = newFont.fontDescriptor.withSymbolicTraits(oldFont.fontDescriptor.symbolicTraits) else {
  20. return
  21. }
  22. let mergedSize = oldFont.pointSize == defaultFontSize ? newFont.pointSize : oldFont.pointSize
  23. let mergedFont = UIFont(descriptor: newFontDescriptor, size: mergedSize)
  24. self.removeAttribute(.font, range: range)
  25. self.addAttribute(.font, value: mergedFont, range: range)
  26. }
  27. self.endEditing()
  28. }
  29. func replaceColor(with newColor: UIColor) {
  30. self.beginEditing()
  31. let defaultColor = UIColor.black
  32. self.enumerateAttribute(.foregroundColor, in: NSRange(location: 0, length: self.length)) { (value, range, _) in
  33. if let oldColor = value as? UIColor, oldColor == defaultColor {
  34. self.addAttribute(.foregroundColor, value: newColor, range: range)
  35. }
  36. }
  37. self.endEditing()
  38. }
  39. func trimmingTrailingNewlinesAndWhitespaces() -> NSMutableAttributedString {
  40. let invertedSet = CharacterSet.whitespacesAndNewlines.inverted
  41. let range = (self.string as NSString).rangeOfCharacter(from: invertedSet, options: .backwards)
  42. let length = range.location == NSNotFound ? 0 : NSMaxRange(range)
  43. return NSMutableAttributedString(attributedString: self.attributedSubstring(from: NSRange(location: 0, length: length)))
  44. }
  45. func trimmingTrailingNewlines() -> NSMutableAttributedString {
  46. let invertedSet = CharacterSet.whitespacesAndNewlines.subtracting(CharacterSet.whitespaces).inverted
  47. let range = (self.string as NSString).rangeOfCharacter(from: invertedSet, options: .backwards)
  48. let length = range.location == NSNotFound ? 0 : NSMaxRange(range)
  49. return NSMutableAttributedString(attributedString: self.attributedSubstring(from: NSRange(location: 0, length: length)))
  50. }
  51. }