Last active
November 15, 2015 08:53
-
-
Save advantis/3dcb4557c45470f23b64 to your computer and use it in GitHub Desktop.
Generic segmented control in Swift
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 | |
class SegmentedControl: UIControl { | |
private let action = Selector("selectSegment:") | |
@IBOutlet | |
private var segments: [UIButton] = [] { | |
didSet { | |
segments.sortInPlace { $0.tag < $1.tag } | |
subscribe(segments) | |
} | |
} | |
var selectedSegmentIndex: Int = 0 { | |
didSet { selectSegmentAtIndex(selectedSegmentIndex) } | |
} | |
override var enabled: Bool { | |
didSet { segments.forEach { $0.enabled = enabled } } | |
} | |
private func subscribe(segments: [UIButton]) { | |
segments.forEach { | |
$0.addTarget(self, action: action, forControlEvents: .TouchDown) | |
} | |
} | |
private dynamic func selectSegment(sender: UIButton) { | |
if let index = segments.indexOf(sender) where index != selectedSegmentIndex { | |
selectedSegmentIndex = index | |
sendActionsForControlEvents(.ValueChanged) | |
} | |
} | |
private func selectSegmentAtIndex(index: Int) { | |
segments.forEach { $0.selected = false } | |
if index != UISegmentedControlNoSegment { | |
segments[index].selected = true | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment