コピペ: NSControlにアクション用のPublisherを返すようにする

形式
C
投稿日時
2020-01-10 15:21
公開期間
無期限
  1. struct ActioinSubscription: Subscription {
  2. let combineIdentifier = CombineIdentifier()
  3. let actionReciever: ActionReciever
  4. func request(_ demand: Subscribers.Demand) {}
  5. func cancel() {
  6. actionReciever.handler = nil
  7. }
  8. }
  9. internal final class ActionReciever: NSObject {
  10. private(set) weak var target: NSControl!
  11. var handler: ((NSControl) -> Void)?
  12. init(target: NSControl) {
  13. self.target = target
  14. target.target = self
  15. target.action = action
  16. }
  17. @IBAction private func action(_ sender: Any) {
  18. handler(target)
  19. }
  20. }
  21. extension NSControl {
  22. struct ControlActionPublisher: Combine.Publisher {
  23. typealias Output = NSControl
  24. typealias Failure = Never
  25. let actionReciever: ActionReciever
  26. init(target: Output) {
  27. self.actionReciever = ActionReciever(target: target)
  28. }
  29. func receive<S>(subscriber: S) where S : Subscriber, Failure == S.Failure, Output == S.Input {
  30. actionReciever.handler = { control in _ = subscriber.receive(control) }
  31. subscriber.receive(subscription: ActioinSubscription(actionReciever: actionReciever))
  32. }
  33. }
  34. func actionPublisher() -> ControlActionPublisher {
  35. ActionReciever(target: self)
  36. }
  37. }
ダウンロード 印刷用表示

このコピペの URL

JavaScript での埋め込み

iframe での埋め込み

元のテキスト