Skip to content

Instantly share code, notes, and snippets.

@mbeaty
Forked from anonymous/ViewController.swift
Last active May 19, 2016 07:35
Show Gist options
  • Save mbeaty/78e13ec92e409c515e522787aa24a095 to your computer and use it in GitHub Desktop.
Save mbeaty/78e13ec92e409c515e522787aa24a095 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.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: {
button1.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.
}
}
typealias ButtonCallback = (() -> ())
protocol UIActionButton {
func on(event : UIControlEvents, then callback: ButtonCallback)
}
final class UICallbackButton : UIButton, UIActionButton {
var buttonCallback: ButtonCallback!
func on(event : UIControlEvents, then callback: () -> ()) {
buttonCallback = callback
self.addTarget(self, action: #selector(UICallbackButton.executeCallback(_:)), forControlEvents: event)
}
func executeCallback (_ : UIButton) {
buttonCallback()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment