Created
November 13, 2018 15:09
-
-
Save benpackard/eb723750cf9868a9c75a4884c2dd1aa9 to your computer and use it in GitHub Desktop.
Set and get selected enum case from a `UISegmentedControl` without relying on indexes or strings.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
protocol Segmentable: RawRepresentable & CaseIterable { } | |
class EnumeratedSegmentedControl<T: Segmentable>: UISegmentedControl where T.RawValue == String { | |
convenience init() { | |
let items = T.allCases.map { $0.rawValue } | |
self.init(items: items) | |
} | |
var selectedSegment: T? { | |
get { | |
if selectedSegmentIndex == -1 { return nil } | |
guard selectedSegmentIndex < T.allCases.count else { return nil } | |
return Array(T.allCases)[selectedSegmentIndex] | |
} | |
set { | |
if let newValue = newValue { | |
selectedSegmentIndex = T.allCases.map({ $0.rawValue }).index(of: newValue.rawValue) ?? -1 | |
} else { | |
selectedSegmentIndex = -1 | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment