GlucoseEntryTableViewController.swift 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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: AnyObject {
  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(for: glucoseUnit)
  18. return quantityFormatter.numberFormatter
  19. }()
  20. public var glucose: HKQuantity? {
  21. get {
  22. guard let value = value, let doubleValue = Double(value) else {
  23. return nil
  24. }
  25. return HKQuantity(unit: glucoseUnit, doubleValue: doubleValue)
  26. }
  27. set {
  28. if let newValue = newValue {
  29. value = glucoseFormatter.string(from: newValue.doubleValue(for: glucoseUnit))
  30. } else {
  31. value = nil
  32. }
  33. }
  34. }
  35. public weak var glucoseEntryDelegate: GlucoseEntryTableViewControllerDelegate?
  36. public init(glucoseUnit: HKUnit) {
  37. self.glucoseUnit = glucoseUnit
  38. super.init(style: .grouped)
  39. unit = glucoseUnit.shortLocalizedUnitString()
  40. keyboardType = .decimalPad
  41. placeholder = "Enter glucose value"
  42. delegate = self
  43. }
  44. required init?(coder aDecoder: NSCoder) {
  45. fatalError("init(coder:) has not been implemented")
  46. }
  47. }
  48. extension GlucoseEntryTableViewController: TextFieldTableViewControllerDelegate {
  49. public func textFieldTableViewControllerDidEndEditing(_ controller: TextFieldTableViewController) {
  50. glucoseEntryDelegate?.glucoseEntryTableViewControllerDidChangeGlucose(self)
  51. }
  52. public func textFieldTableViewControllerDidReturn(_ controller: TextFieldTableViewController) {
  53. glucoseEntryDelegate?.glucoseEntryTableViewControllerDidChangeGlucose(self)
  54. }
  55. }