Skip to content

Instantly share code, notes, and snippets.

@sergii-frost
Last active August 2, 2017 14:02
Show Gist options
  • Save sergii-frost/157bc0ad78b36baae31b2f6d870986e5 to your computer and use it in GitHub Desktop.
Save sergii-frost/157bc0ad78b36baae31b2f6d870986e5 to your computer and use it in GitHub Desktop.
Swift: Button with closures as actions
let button = FRButton()

button.touchDownAction = {(button: FRButton) in
  print("button touchDownAction")
}

button.touchUpAction = {(button: FRButton) in
  print("button touchUpAction")
}


button.touchExitAction = {(button: FRButton) in
  print("button touchExitAction")
}

//
// Button with:
// - designable cornerRadius
// - designable borderWidth
// - designable borderColor
// - optional actions for touchDown, touchExit, touchUp
//
import UIKit
typealias FRButtonAction = (FRButton) -> Void
@IBDesignable
public class FRButton: UIButton {
var touchDownAction: FRButtonAction?
var touchUpAction: FRButtonAction?
var touchExitAction: FRButtonAction?
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupActions()
}
public override init(frame: CGRect) {
super.init(frame: frame)
setupActions()
}
@IBInspectable var borderWidth: CGFloat = 0.0 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable var borderColor: UIColor? {
didSet {
layer.borderColor = borderColor?.cgColor
}
}
@IBInspectable override var cornerRadius: CGFloat {
didSet {
layer.cornerRadius = cornerRadius
layer.masksToBounds = cornerRadius > 0
}
}
}
extension FRButton {
func setupActions() {
addTarget(self, action: #selector(touchDown(sender:)), for: [.touchDown, .touchDragEnter])
addTarget(self, action: #selector(touchExit(sender:)), for: [.touchCancel, .touchDragExit])
addTarget(self, action: #selector(touchUp(sender:)), for: [.touchUpInside])
}
//actions
func touchDown(sender: FRButton) {
touchDownAction?(sender)
}
func touchExit(sender: FRButton) {
touchExitAction?(sender)
}
func touchUp(sender: FRButton) {
touchUpAction?(sender)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment