forked from Ramotion/reel-search
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TextFieldReactor.swift
104 lines (80 loc) · 2.6 KB
/
TextFieldReactor.swift
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
//
// RAMReel.swift
// RAMReel
//
// Created by Mikhail Stepkin on 4/2/15.
// Copyright (c) 2015 Ramotion. All rights reserved.
//
import Foundation
import UIKit
// MARK: - Text field reactor operators
precedencegroup RPrecedence {
higherThan: BitwiseShiftPrecedence
}
infix operator <&> : RPrecedence
/**
Links text field to data flow
- parameters:
- left: Text field.
- right: `DataFlow` object.
- returns: `TextFieldReactor` object
*/
public func <&> <FlowDataSource, FlowDataDestination>
(left: UITextField, right: DataFlow<FlowDataSource, FlowDataDestination>) -> TextFieldReactor<FlowDataSource, FlowDataDestination>
where
FlowDataSource.ResultType == FlowDataDestination.DataType
{
return TextFieldReactor(textField: left, dataFlow: right)
}
// MARK: - Text field reactor
/**
TextFieldReactor
--
Implements reactive handling text field editing and passes editing changes to data flow
*/
public struct TextFieldReactor
<
DS: FlowDataSource,
DD: FlowDataDestination>
where
DS.ResultType == DD.DataType,
DS.QueryType == String
{
let textField : UITextField
let dataFlow : DataFlow<DS, DD>
fileprivate let editingTarget: TextFieldTarget
fileprivate init(textField: UITextField, dataFlow: DataFlow<DS, DD>) {
self.textField = textField
self.dataFlow = dataFlow
self.editingTarget = TextFieldTarget(controlEvents: UIControl.Event.editingChanged, textField: textField) {
if let text = $0.text {
dataFlow.transport(text)
}
}
}
}
final class TextFieldTarget: NSObject {
static let actionSelector = #selector(TextFieldTarget.action(_:))
typealias HookType = (UITextField) -> ()
override init() {
super.init()
}
init(controlEvents:UIControl.Event, textField: UITextField, hook: @escaping HookType) {
super.init()
self.beTargetFor(textField, controlEvents: controlEvents, hook: hook)
}
var hooks: [UITextField: HookType] = [:]
func beTargetFor(_ textField: UITextField, controlEvents:UIControl.Event, hook: @escaping HookType) {
textField.addTarget(self, action: TextFieldTarget.actionSelector, for: controlEvents)
hooks[textField] = hook
}
deinit {
for (textField, _) in hooks {
textField.removeTarget(self, action: TextFieldTarget.actionSelector, for: UIControl.Event.allEvents)
}
}
@objc func action(_ textField: UITextField) {
let hook = hooks[textField]
hook?(textField)
}
}