Skip to content

Instantly share code, notes, and snippets.

Created May 18, 2016 16:21
Show Gist options
  • Save anonymous/baa4f873b33403f0798445d50dbd7550 to your computer and use it in GitHub Desktop.
Save anonymous/baa4f873b33403f0798445d50dbd7550 to your computer and use it in GitHub Desktop.
import UIKit
class ViewController: UIViewController {
var count = 1
override func viewDidLoad() {
super.viewDidLoad()
// Button 1
let button = UICallbackButton(frame: CGRect(x: 60, y: 30, width: 200, height: 60))
button.backgroundColor = UIColor.orangeColor()
button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
button.setTitle("Title Default", forState: .Normal)
button.on(.TouchUpInside, then: {(button : UIButton) in
button.setTitle("Title \(self.count)", forState: .Normal)
self.count = self.count + 1
})
self.view.addSubview(button)
// Button 2
let button1 = UICallbackButton(frame: CGRect(x: 60, y: 160, width: 200, height: 60))
button1.backgroundColor = UIColor.blackColor()
button1.setTitleColor(UIColor.whiteColor(), forState: .Normal)
button1.setTitle("Value Default", forState: .Normal)
button1.on(.TouchUpInside, then: {(button : UIButton) in
button.setTitle("Value \(self.count)", forState: .Normal)
self.count = self.count + 1
})
self.view.addSubview(button1)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
protocol UIActionButton {
func on(event : UIControlEvents, then callback: (button : UIButton) -> Void)
}
final class UICallbackButton : UIButton, UIActionButton {
func on(event : UIControlEvents, then callback: (button : UIButton) -> Void) {
self.addTarget(self, action: #selector(UICallbackButton.executeCallback(_:callback:)), forControlEvents: event)
}
func executeCallback (_ : UIButton, callback: (button : UIButton) -> Void) {
callback(button: self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment