SegmentedControlTableViewCell.swift 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. //
  2. // SegmentedControlTableViewCell.swift
  3. // LoopKitUI
  4. //
  5. // Created by Michael Pangburn on 7/14/20.
  6. // Copyright © 2020 LoopKit Authors. All rights reserved.
  7. //
  8. import UIKit
  9. open class SegmentedControlTableViewCell: UITableViewCell {
  10. public var segmentedControl = UISegmentedControl(frame: .zero)
  11. public var options: [String] = [] {
  12. didSet {
  13. segmentedControl.removeAllSegments()
  14. for (index, option) in options.enumerated() {
  15. segmentedControl.insertSegment(withTitle: option, at: index, animated: false)
  16. }
  17. }
  18. }
  19. private var select: (_ index: Int) -> Void = { _ in }
  20. public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
  21. super.init(style: .value1, reuseIdentifier: Self.className)
  22. setUp()
  23. }
  24. required public init?(coder: NSCoder) {
  25. super.init(coder: coder)
  26. setUp()
  27. }
  28. private func setUp() {
  29. contentView.addSubview(segmentedControl)
  30. segmentedControl.translatesAutoresizingMaskIntoConstraints = false
  31. NSLayoutConstraint.activate([
  32. segmentedControl.trailingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.trailingAnchor),
  33. segmentedControl.centerYAnchor.constraint(equalTo: contentView.centerYAnchor),
  34. segmentedControl.leadingAnchor.constraint(equalTo: textLabel?.trailingAnchor ?? contentView.leadingAnchor)
  35. ])
  36. }
  37. override open func layoutSubviews() {
  38. super.layoutSubviews()
  39. contentView.layoutMargins.left = separatorInset.left
  40. contentView.layoutMargins.right = separatorInset.left
  41. }
  42. override open func prepareForReuse() {
  43. super.prepareForReuse()
  44. segmentedControl.removeTarget(nil, action: nil, for: .valueChanged)
  45. select = { _ in }
  46. }
  47. public func onSelection(_ select: @escaping (_ index: Int) -> Void) {
  48. self.select = select
  49. segmentedControl.addTarget(self, action: #selector(handleSelection), for: .valueChanged)
  50. }
  51. @objc private func handleSelection() {
  52. select(segmentedControl.selectedSegmentIndex)
  53. }
  54. }