KMBaseTextFormatter.swift 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. //
  2. // KMBaseTextFormatter.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by lizhe on 2022/12/12.
  6. //
  7. import Cocoa
  8. class KMBaseTextFormatter: NumberFormatter {
  9. var model: KMBaseTextFieldModel = KMBaseTextFieldModel()
  10. override func isPartialStringValid(_ partialStringPtr: AutoreleasingUnsafeMutablePointer<NSString>, proposedSelectedRange proposedSelRangePtr: NSRangePointer?, originalString origString: String, originalSelectedRange origSelRange: NSRange, errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>?) -> Bool {
  11. let data = self.model
  12. var partialString = partialStringPtr.pointee
  13. if partialString.debugDescription.isEmpty {
  14. return true
  15. }
  16. if (data.onlyNumber) {
  17. var regex: NSString = "^[0123456789.]*$"
  18. if !data.specialChart.debugDescription.isEmpty {
  19. regex = NSString(format: "^[0123456789%@]*$", data.specialChart)
  20. }
  21. let predicate = NSPredicate.init(format: "SELF MATCHES %@", regex)
  22. if !predicate.evaluate(with: partialString) {
  23. return false
  24. }
  25. if !data.specialChart.debugDescription.isEmpty {
  26. partialString = partialString.replacingOccurrences(of: data.specialChart, with: "") as NSString
  27. }
  28. if (Int(partialString.debugDescription) ?? 0 < data.minValue ||
  29. Int(partialString.debugDescription) ?? 0 > data.maxValue) {
  30. return false
  31. }
  32. }
  33. let newRange: NSRange = proposedSelRangePtr!.pointee
  34. if (NSMaxRange(origSelRange) > NSMaxRange(newRange)) {
  35. return true
  36. }
  37. return true
  38. }
  39. override func attributedString(for obj: Any, withDefaultAttributes attrs: [NSAttributedString.Key : Any]? = nil) -> NSAttributedString? {
  40. return nil
  41. }
  42. }