Last active
May 10, 2016 00:36
-
-
Save roymckenzie/764e14e628dbc8d0b70a159cb571eec8 to your computer and use it in GitHub Desktop.
PLToggleControl
This file contains 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
@IBDesignable class PLToggleControl: UIControl { | |
var items = [String]() | |
var labels = [UILabel]() | |
var activeLineView = UIView() | |
@IBInsepctable var activeTextColor: UIColor = .whiteColor() | |
@IBInspectable var inactiveTextColor: UIColor = .grayColor() | |
@IBInspectable var buttonColor: UIColor = .blackColor() | |
@IBInspectable var activeLineColor: UIColor = .blackColor() | |
var selectedIndex = 0 { | |
didSet { | |
displaySelectedIndex() | |
} | |
} | |
override init(frame: CGRect) { | |
super.init(frame: frame) | |
setupControl() | |
} | |
required init?(coder aDecoder: NSCoder) { | |
super.init(coder: aDecoder) | |
setupControl() | |
} | |
override func layoutSubviews() { | |
super.layoutSubviews() | |
let labelHeight = bounds.height | |
let labelWidth = bounds.width / CGFloat(labels.count) | |
labels.forEach { label in | |
let xPosition = CGFloat(labels.indexOf(label)!) * labelWidth | |
label.frame = CGRect(x: xPosition, y: 0, width: labelWidth, height: labelHeight) | |
} | |
setupActiveLine() | |
displaySelectedIndex() | |
} | |
override func beginTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool { | |
let location = touch.locationInView(self) | |
for (i, label) in labels.enumerate() { | |
if label.frame.contains(location) { | |
selectedIndex = i | |
} | |
} | |
sendActionsForControlEvents(.ValueChanged) | |
return true | |
} | |
private func setupControl() { | |
backgroundColor = buttonColor | |
setupLabels() | |
} | |
private func setupLabels() { | |
labels.forEach { $0.removeFromSuperview() } | |
labels.removeAll(keepCapacity: true) | |
items.forEach { item in | |
let label = UILabel() | |
label.text = item | |
label.textAlignment = .Center | |
label.textColor = inactiveTextColor | |
label.font = UIFont.systemFontOfSize(15) | |
addSubview(label) | |
labels.append(label) | |
} | |
} | |
private func setupActiveLine() { | |
activeLineView.backgroundColor = activeLineColor | |
let yPosition = bounds.height - 1.5 | |
let width = bounds.width / CGFloat(labels.count) | |
activeLineView.frame = CGRect(x: 0, y: yPosition, width: width, height: 1.5) | |
addSubview(activeLineView) | |
} | |
private func displaySelectedIndex() { | |
labels.forEach { $0.textColor = inactiveTextColor } | |
let label = labels[selectedIndex] | |
label.textColor = activeTextColor | |
let newXOrigin = label.frame.origin.x | |
UIView.animateWithDuration(0.2) { | |
self.activeLineView.frame.origin.x = newXOrigin | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment