Skip to content

Instantly share code, notes, and snippets.

@nathantannar4
Created December 21, 2018 00:43
Show Gist options
  • Save nathantannar4/036e67efef7da990979f75424cc14a50 to your computer and use it in GitHub Desktop.
Save nathantannar4/036e67efef7da990979f75424cc14a50 to your computer and use it in GitHub Desktop.
Re-Engineering Switch Outline
class Switch: UIControl {
var isOn: Bool
// Determines if the thumbLayer stretches on touchDown
var isStretchEnable: Bool
// Border of the trackLayer, this also determines the inset of the innerLayer
var borderWidth: CGFloat
// We can use these properties later to adjust the layout to make the switch
// have a Material UI design
var trackTopBottomPadding: CGFloat
var thumbRadiusPadding: CGFloat
var onTintColor: UIColor
var offTintColor: UIColor
var thumbTintColor: UIColor
let trackLayer: CALayer
let innerLayer: CALayer
let thumbLayer: CALayer
private var isTouchDown: Bool
override init(frame: CGRect) {
super.init(frame: frame)
controlDidLoad()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
controlDidLoad()
}
func controlDidLoad() {
layer.addSublayer(trackLayer)
layer.addSublayer(innerLayer)
layer.addSublayer(thumbLayer)
addTouchHandlers()
layoutSublayers(of: layer)
}
override func layoutSublayers(of layer: CALayer) {
super.layoutSublayers(of: layer)
layoutTrackLayer(for: layer.bounds)
layoutInnerLayer(for: layer.bounds)
layoutThumbLayer(for: layer.bounds)
}
func stateDidChange() {
//...
}
func setOn(_ on: Bool, animated: Bool) {
isOn = on
//...
}
// MARK: - Touches
private func addTouchHandlers() {
addTarget(self, action: #selector(touchDown), for: [.touchDown, .touchDragEnter])
addTarget(self, action: #selector(touchUp), for: [.touchUpInside])
addTarget(self, action: #selector(touchEnded), for: [.touchDragExit, .touchCancel])
}
@objc
private func touchDown() {
isTouchDown = true
layoutSublayers(of: layer)
}
@objc
private func touchUp() {
isOn.toggle()
touchEnded()
}
@objc
private func touchEnded() {
isTouchDown = false
layoutSublayers(of: layer)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment