杨锴
2025-04-16 09a372bc45fde16fd42257ab6f78b8deeecf720b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
//
//  ControlTarget.swift
//  RxCocoa
//
//  Created by Krunoslav Zaher on 2/21/15.
//  Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
 
#if os(iOS) || os(tvOS) || os(visionOS) || os(macOS)
 
import RxSwift
 
#if os(iOS) || os(tvOS) || os(visionOS)
    import UIKit
 
    typealias Control = UIKit.UIControl
#elseif os(macOS)
    import Cocoa
 
    typealias Control = Cocoa.NSControl
#endif
 
// This should be only used from `MainScheduler`
final class ControlTarget: RxTarget {
    typealias Callback = (Control) -> Void
 
    let selector: Selector = #selector(ControlTarget.eventHandler(_:))
 
    weak var control: Control?
#if os(iOS) || os(tvOS) || os(visionOS)
    let controlEvents: UIControl.Event
#endif
    var callback: Callback?
    #if os(iOS) || os(tvOS) || os(visionOS)
    init(control: Control, controlEvents: UIControl.Event, callback: @escaping Callback) {
        MainScheduler.ensureRunningOnMainThread()
 
        self.control = control
        self.controlEvents = controlEvents
        self.callback = callback
 
        super.init()
 
        control.addTarget(self, action: selector, for: controlEvents)
 
        let method = self.method(for: selector)
        if method == nil {
            rxFatalError("Can't find method")
        }
    }
#elseif os(macOS)
    init(control: Control, callback: @escaping Callback) {
        MainScheduler.ensureRunningOnMainThread()
 
        self.control = control
        self.callback = callback
 
        super.init()
 
        control.target = self
        control.action = self.selector
 
        let method = self.method(for: self.selector)
        if method == nil {
            rxFatalError("Can't find method")
        }
    }
#endif
 
    @objc func eventHandler(_ sender: Control!) {
        if let callback = self.callback, let control = self.control {
            callback(control)
        }
    }
 
    override func dispose() {
        super.dispose()
#if os(iOS) || os(tvOS) || os(visionOS)
        self.control?.removeTarget(self, action: self.selector, for: self.controlEvents)
#elseif os(macOS)
        self.control?.target = nil
        self.control?.action = nil
#endif
        self.callback = nil
    }
}
 
#endif