Created
August 6, 2020 16:24
-
-
Save TizianoCoroneo/ba95bab8fe46f693ddba0cf2cca37051 to your computer and use it in GitHub Desktop.
Closure based Selector
This file contains 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 | |
import PlaygroundSupport | |
import UIKit | |
final class Sel { | |
static let target = DummyClass.shared | |
final class DummyClass { | |
static let shared = DummyClass() | |
private init() {} | |
} | |
let action: () -> Void | |
@objc func objcAction() { self.action() } | |
init(_ action: @escaping () -> Void) { | |
self.action = action | |
} | |
} | |
func Selector(_ action: @escaping () -> Void) -> ObjectiveC.Selector { | |
var selectorString = UUID().uuidString | |
selectorString.removeAll(where: { $0 == "-" }) | |
let newSelector = NSSelectorFromString(selectorString) | |
let actionMethod = class_getInstanceMethod( | |
Sel.self, | |
#selector(Sel.objcAction))! | |
let typeEncoding = method_getTypeEncoding(actionMethod)! | |
let myBlock: @convention(block) () -> Void = { action() } | |
let imp = imp_implementationWithBlock( | |
unsafeBitCast(myBlock, to: AnyObject.self)) | |
class_addMethod( | |
Sel.DummyClass.self, | |
newSelector, | |
imp, | |
typeEncoding) | |
return newSelector | |
} | |
let uiButton = UIButton(frame: .init(x: 0, y: 0, width: 200, height: 100)) | |
uiButton.setTitle("Test button", for: .normal) | |
uiButton.addTarget( | |
Sel.target, | |
action: Selector { | |
print("YEAH") | |
}, | |
for: .touchUpInside) | |
PlaygroundPage.current.needsIndefiniteExecution = true | |
PlaygroundPage.current.setLiveView(uiButton) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment