GlucoseEntryTableViewController.swift 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. //
  2. // GlucoseEntryTableViewController.swift
  3. // LoopKitUI
  4. //
  5. // Created by Michael Pangburn on 11/24/18.
  6. // Copyright © 2018 LoopKit Authors. All rights reserved.
  7. //
  8. import UIKit
  9. import HealthKit
  10. import LoopKit
  11. public protocol GlucoseEntryTableViewControllerDelegate: class {
  12. func glucoseEntryTableViewControllerDidChangeGlucose(_ controller: GlucoseEntryTableViewController)
  13. }
  14. public class GlucoseEntryTableViewController: TextFieldTableViewController {
  15. let glucoseUnit: HKUnit
  16. private lazy var glucoseFormatter: NumberFormatter = {
  17. let quantityFormatter = QuantityFormatter()
  18. quantityFormatter.setPreferredNumberFormatter(for: glucoseUnit)
  19. return quantityFormatter.numberFormatter
  20. }()
  21. public var glucose: HKQuantity? {
  22. get {
  23. guard let value = value, let doubleValue = Double(value) else {
  24. return nil
  25. }
  26. return HKQuantity(unit: glucoseUnit, doubleValue: doubleValue)
  27. }
  28. set {
  29. if let newValue = newValue {
  30. value = glucoseFormatter.string(from: newValue.doubleValue(for: glucoseUnit))
  31. } else {
  32. value = nil
  33. }
  34. }
  35. }
  36. public weak var glucoseEntryDelegate: GlucoseEntryTableViewControllerDelegate?
  37. public init(glucoseUnit: HKUnit) {
  38. self.glucoseUnit = glucoseUnit
  39. super.init(style: .grouped)
  40. unit = glucoseUnit.shortLocalizedUnitString()
  41. keyboardType = .decimalPad
  42. placeholder = "Enter glucose value"
  43. delegate = self
  44. }
  45. required init?(coder aDecoder: NSCoder) {
  46. fatalError("init(coder:) has not been implemented")
  47. }
  48. }
  49. extension GlucoseEntryTableViewController: TextFieldTableViewControllerDelegate {
  50. public func textFieldTableViewControllerDidEndEditing(_ controller: TextFieldTableViewController) {
  51. glucoseEntryDelegate?.glucoseEntryTableViewControllerDidChangeGlucose(self)
  52. }
  53. public func textFieldTableViewControllerDidReturn(_ controller: TextFieldTableViewController) {
  54. glucoseEntryDelegate?.glucoseEntryTableViewControllerDidChangeGlucose(self)
  55. }
  56. }