Skip to content

Instantly share code, notes, and snippets.

@ferbass
Created May 3, 2016 04:14
Show Gist options
  • Save ferbass/eb1f08d72e323fd818dfb03a071f419e to your computer and use it in GitHub Desktop.
Save ferbass/eb1f08d72e323fd818dfb03a071f419e to your computer and use it in GitHub Desktop.
Adding a closure as target to a UIButton
import UIKit
extension UIButton {
private func actionHandleBlock(action:(() -> Void)? = nil) {
struct __ {
static var action :(() -> Void)?
}
if action != nil {
__.action = action
} else {
__.action?()
}
}
@objc private func triggerActionHandleBlock() {
self.actionHandleBlock()
}
func actionHandle(controlEvents control :UIControlEvents, ForAction action:() -> Void) {
self.actionHandleBlock(action)
self.addTarget(self, action: "triggerActionHandleBlock", forControlEvents: control)
}
let button = UIButton()
button.actionHandle(controlEvents: UIControlEvents.TouchUpInside,
ForAction:{() -> Void in
print("Touch")
})
@sunilsharma08
Copy link

sunilsharma08 commented May 28, 2017

Can you please explain this function

private func actionHandleBlock(action:(() -> Void)? = nil) {
        struct __ {
            static var action :(() -> Void)?
        }
        if action != nil {
            __.action = action
        } else {
            __.action?()
        }
}

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