NSAttributedString+Extension.swift 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. //
  2. // NSAttributedString+Extension.swift
  3. // QuickSearchLocation
  4. //
  5. // Created by Destiny on 2024/11/27.
  6. //
  7. import UIKit
  8. extension NSAttributedString {
  9. func setRangeFontText(font: UIFont, range: NSRange) -> NSAttributedString {
  10. return setSpecificRangeTextMoreAttributes(attributes: [NSAttributedString.Key.font : font], range: range)
  11. }
  12. func setSpecificTextColor(_ text: String, color: UIColor) -> NSAttributedString {
  13. return setSpecificTextMoreAttributes(text, attributes: [NSAttributedString.Key.foregroundColor : color])
  14. }
  15. func setSpecificRangeTextMoreAttributes(attributes: Dictionary<NSAttributedString.Key, Any>, range: NSRange) -> NSAttributedString {
  16. let mutableAttributedString = NSMutableAttributedString(attributedString: self)
  17. for name in attributes.keys {
  18. mutableAttributedString.addAttribute(name, value: attributes[name] ?? "", range: range)
  19. }
  20. return mutableAttributedString
  21. }
  22. func setSpecificTextColorFont(_ text: String, color: UIColor, font: UIFont) -> NSAttributedString {
  23. return setSpecificTextMoreAttributes(text, attributes: [NSAttributedString.Key.foregroundColor : color, NSAttributedString.Key.font : font])
  24. }
  25. func setSpecificTextMoreAttributes(_ text: String, attributes: Dictionary<NSAttributedString.Key, Any>) -> NSAttributedString {
  26. let mutableAttributedString = NSMutableAttributedString(attributedString: self)
  27. let rangeArray = getStringRangeArray(with: [text])
  28. if !rangeArray.isEmpty {
  29. for name in attributes.keys {
  30. for range in rangeArray {
  31. mutableAttributedString.addAttribute(name, value: attributes[name] ?? "", range: range)
  32. }
  33. }
  34. }
  35. return mutableAttributedString
  36. }
  37. private func getStringRangeArray(with textArray: Array<String>) -> Array<NSRange> {
  38. var rangeArray = Array<NSRange>()
  39. // 遍历
  40. for str in textArray {
  41. if self.string.contains(str) {
  42. let subStrArr = self.string.components(separatedBy: str)
  43. var subStrIndex = 0
  44. for i in 0 ..< (subStrArr.count - 1) {
  45. let subDivisionStr = subStrArr[i]
  46. if i == 0 {
  47. subStrIndex += (subDivisionStr.lengthOfBytes(using: .unicode) / 2)
  48. } else {
  49. subStrIndex += (subDivisionStr.lengthOfBytes(using: .unicode) / 2 + str.lengthOfBytes(using: .unicode) / 2)
  50. }
  51. let newRange = NSRange(location: subStrIndex, length: str.count)
  52. rangeArray.append(newRange)
  53. }
  54. }
  55. }
  56. return rangeArray
  57. }
  58. }