Created
March 16, 2018 10:22
-
-
Save janodev/de54d10224b1bee1d0be5aa0a8b9b352 to your computer and use it in GitHub Desktop.
A delegate implemented with generics and a static method
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
public class ControlAction { | |
let closure: ()->() | |
init (_ closure: @escaping ()->()) { | |
self.closure = closure | |
} | |
@objc func invoke () { | |
closure() | |
} | |
} | |
extension UIControl | |
{ | |
/// Add a closure to be fired in response to a control event. | |
public func add(for controlEvents: UIControlEvents, _ closure: @escaping ()->()) { | |
let controlAction = ControlAction(closure) | |
addTarget(controlAction, action: #selector(ControlAction.invoke), for: controlEvents) | |
objc_setAssociatedObject(self, UUID().uuidString, controlAction, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
// Encapsulate creation and configuration of an object. | |
func create<Type>(_ value : Type, block: (_ object: Type) -> Void) -> Type { | |
block(value) | |
return value | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
class ViewController: UIViewController | |
{ | |
private typealias ShakyButton = BouncyButton<ShakeStrategy> | |
private let button = create(ShakyButton(frame: CGRect(x: 50, y: 50, width: 100, height: 100))) { (button) in | |
button.backgroundColor = UIColor.lightGray | |
button.add(for: .touchUpInside, { print("pickles") }) | |
} | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
view.addSubview(button) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment