Swift: Enum with UIControl Example
Here is a quick example showing how to tie in a Swift enum with a UI control. In this case, the UI control is a UISegmentedControl
that is used for switching a UIStackView
in my UI between all of the UIStackViewDistribution
types. The UIStackViewDistribution
enum is currently:
enum UIStackViewDistribution : Int {
case Fill
case FillEqually
case FillProportionally
case EqualSpacing
case EqualCentering
}
The key here is to name the segment titles of the segmented control in the same order according to the enum. So the title for segment 0 is "Fill", the title for segment 1 is "FillEqually", etc. Each time I select a segment, the stack view needs to change it's distribution
property accordingly.
I have an IBAction
wired up for every time a segment gets selected:
@IBAction private func segmentedControlChanged(sender: UISegmentedControl) {
// TODO: Handle sender.selectedSegmentIndex here
// self.stackView.distribution = get distribution
}
The distribution
can be created using the rawValue
of the enum. The UIStackViewDistribution
enum has a rawValue
of type Int
, so here I used the selectedSegmentIndex
for that parameter:
@IBAction private func segmentedControlChanged(sender: UISegmentedControl) {
let distribution = UIStackViewDistribution(rawValue: sender.selectedSegmentIndex)
// TODO: set self.stackView.distribution here
}
Initializing an enum with a rawValue
will return an optional so it needs to be unwrapped first:
@IBAction private func segmentedControlChanged(sender: UISegmentedControl) {
guard let distribution = UIStackViewDistribution(rawValue: sender.selectedSegmentIndex) else {
return
}
// TODO: set self.stackView.distribution here
}
Finally, set the distribution on the stackView
:
@IBAction private func segmentedControlChanged(sender: UISegmentedControl) {
guard let distribution = UIStackViewDistribution(rawValue: sender.selectedSegmentIndex) else {
return
}
UIView.animateWithDuration(0.5) {
self.stackView.distribution = distribution
}
}