Skip to content

Instantly share code, notes, and snippets.

@nicolastinkl
Last active April 4, 2017 23:34
Show Gist options
  • Save nicolastinkl/e33ab89b56b27af2808b to your computer and use it in GitHub Desktop.
Save nicolastinkl/e33ab89b56b27af2808b to your computer and use it in GitHub Desktop.
how to use 'Currying' and implement UIControl
protocol TargetAction{
func performAction()
}
struct TargetActionWrapper<T:AnyObject>:TargetAction {
weak var target : T?
var action:(T)->()->()
func performAction() {
if let t = target{
action(t)() // real return a function ()->()
}
}
}
enum ControlsEvents{
case TouchUpInside
case ValueChanged
case TouchDownOutside
}
class TKControl {
var actions = [ControlsEvents:TargetAction]()
//settargetaction Target/Action/ControlStatus
func setTarget<T : AnyObject>(target:T,action:(T)->()->(),controlEvent:ControlsEvents)
{
let item = TargetActionWrapper(target: target, action: action)
actions[controlEvent] = item
}
//add events
func performActionForControlEvent(controlEvent: ControlsEvents) {
actions[controlEvent]?.performAction()
}
//remove events
func removeTargetForControlEvent(controlEvent: ControlsEvents) {
actions[controlEvent] = nil
}
func click()
{
}
func log()
{
// println("some body jiekuan summary")
}
}
@nicolastinkl
Copy link
Author


class ViewController: UIViewController {

    func onButtonTap() -> () {
        println("Button was tapped")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        var button  = TKControl()

        button.log()

        button.setTarget(self, action: ViewController.onButtonTap, controlEvent: ControlsEvents.TouchUpInside)

        println("count : \(button.actions.count)")
        // Do any additional setup after loading the view, typically from a nib.
    }


    @IBAction func seeLog(sender: AnyObject) {

        UIAlertView(title: "title", message: "ok", delegate: nil, cancelButtonTitle: "ok").show()
        TKControl().click();
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


@freennnn
Copy link

freennnn commented Apr 4, 2017

is setting button.setTarget(self, action: ViewController.onButtonTap, controlEvent: ControlsEvents.TouchUpInside) enough? Who is going to call func performActionForControlEvent(controlEvent: ControlsEvents)?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment