RileyLinkDeviceTableViewCell.swift 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. //
  2. // RileyLinkDeviceTableViewCell.swift
  3. // Naterade
  4. //
  5. // Created by Nathan Racklyeft on 8/29/15.
  6. // Copyright © 2015 Nathan Racklyeft. All rights reserved.
  7. //
  8. import CoreBluetooth
  9. import UIKit
  10. public class RileyLinkDeviceTableViewCell: UITableViewCell {
  11. public var connectSwitch: UISwitch?
  12. public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
  13. super.init(style: .value1, reuseIdentifier: reuseIdentifier)
  14. setup()
  15. }
  16. public required init?(coder aDecoder: NSCoder) {
  17. super.init(coder: aDecoder)
  18. }
  19. public override func awakeFromNib() {
  20. super.awakeFromNib()
  21. setup()
  22. }
  23. private func setup() {
  24. // Manually layout the switch with an 8pt left margin
  25. // TODO: Adjust appropriately for RTL
  26. let connectSwitch = UISwitch(frame: .zero)
  27. connectSwitch.sizeToFit()
  28. connectSwitch.frame = connectSwitch.frame.offsetBy(dx: 8, dy: 0)
  29. var switchFrame = connectSwitch.frame
  30. switchFrame.origin = .zero
  31. switchFrame.size.width += 8
  32. let switchContainer = UIView(frame: switchFrame)
  33. switchContainer.addSubview(connectSwitch)
  34. self.connectSwitch = connectSwitch
  35. accessoryView = switchContainer
  36. accessoryType = .disclosureIndicator
  37. }
  38. override public func layoutSubviews() {
  39. super.layoutSubviews()
  40. contentView.layoutMargins.left = separatorInset.left
  41. contentView.layoutMargins.right = separatorInset.left
  42. }
  43. public func configureCellWithName(_ name: String?, signal: String?, peripheralState: CBPeripheralState?) {
  44. textLabel?.text = name
  45. if peripheralState == .connecting {
  46. detailTextLabel?.text = "..."
  47. } else {
  48. detailTextLabel?.text = " \(signal ?? "") "
  49. }
  50. if let state = peripheralState {
  51. switch state {
  52. case .connected:
  53. connectSwitch?.isOn = true
  54. connectSwitch?.isEnabled = true
  55. case .connecting:
  56. connectSwitch?.isOn = true
  57. connectSwitch?.isEnabled = true
  58. case .disconnected:
  59. connectSwitch?.isOn = false
  60. connectSwitch?.isEnabled = true
  61. case .disconnecting:
  62. fallthrough
  63. @unknown default:
  64. connectSwitch?.isOn = false
  65. connectSwitch?.isEnabled = false
  66. }
  67. } else {
  68. connectSwitch?.isHidden = true
  69. }
  70. }
  71. public override func prepareForReuse() {
  72. super.prepareForReuse()
  73. connectSwitch?.removeTarget(nil, action: nil, for: .valueChanged)
  74. }
  75. }