Skip to content

Instantly share code, notes, and snippets.

@TizianoCoroneo
Created August 6, 2020 16:24
Show Gist options
  • Save TizianoCoroneo/ba95bab8fe46f693ddba0cf2cca37051 to your computer and use it in GitHub Desktop.
Save TizianoCoroneo/ba95bab8fe46f693ddba0cf2cca37051 to your computer and use it in GitHub Desktop.
Closure based Selector
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