forked from LoopKit/LoopKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSegmentedControlTableViewCell.swift
More file actions
71 lines (54 loc) · 2.12 KB
/
SegmentedControlTableViewCell.swift
File metadata and controls
71 lines (54 loc) · 2.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
//
// SegmentedControlTableViewCell.swift
// LoopKitUI
//
// Created by Michael Pangburn on 7/14/20.
// Copyright © 2020 LoopKit Authors. All rights reserved.
//
import UIKit
open class SegmentedControlTableViewCell: UITableViewCell {
public var segmentedControl = UISegmentedControl(frame: .zero)
public var options: [String] = [] {
didSet {
segmentedControl.removeAllSegments()
for (index, option) in options.enumerated() {
segmentedControl.insertSegment(withTitle: option, at: index, animated: false)
}
}
}
private var select: (_ index: Int) -> Void = { _ in }
public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: .value1, reuseIdentifier: Self.className)
setUp()
}
required public init?(coder: NSCoder) {
super.init(coder: coder)
setUp()
}
private func setUp() {
contentView.addSubview(segmentedControl)
segmentedControl.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
segmentedControl.trailingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.trailingAnchor),
segmentedControl.centerYAnchor.constraint(equalTo: contentView.centerYAnchor),
segmentedControl.leadingAnchor.constraint(equalTo: textLabel?.trailingAnchor ?? contentView.leadingAnchor)
])
}
override open func layoutSubviews() {
super.layoutSubviews()
contentView.layoutMargins.left = separatorInset.left
contentView.layoutMargins.right = separatorInset.left
}
override open func prepareForReuse() {
super.prepareForReuse()
segmentedControl.removeTarget(nil, action: nil, for: .valueChanged)
select = { _ in }
}
public func onSelection(_ select: @escaping (_ index: Int) -> Void) {
self.select = select
segmentedControl.addTarget(self, action: #selector(handleSelection), for: .valueChanged)
}
@objc private func handleSelection() {
select(segmentedControl.selectedSegmentIndex)
}
}