-
Notifications
You must be signed in to change notification settings - Fork 184
/
RAMReel.swift
461 lines (365 loc) · 16 KB
/
RAMReel.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
//
// RAMReel.swift
// RAMReel
//
// Created by Mikhail Stepkin on 4/21/15.
// Copyright (c) 2015 Ramotion. All rights reserved.
//
import UIKit
// MARK: - String conversions
/**
Renderable
--
Types that implement this protocol are expected to have string representation.
This protocol is separated from Printable and it's description property on purpose.
*/
public protocol Renderable {
/**
Implement this method in order to be able to put data to textField field
Simplest implementation may return just object description
*/
func render() -> String
}
extension String: Renderable {
/// String is trivially renderable: it renders to itself.
public func render() -> String {
return self
}
}
/**
Parsable
--
Types that implement this protocol are expected to be constructible from string
*/
public protocol Parsable {
/**
Implement this method in order to be able to construct your data from string
- parameter string: String to parse.
- returns: Value of type, implementing this protocol if successful, `nil` otherwise.
*/
static func parse(_ string: String) -> Self?
}
extension String: Parsable {
/**
String is trivially parsable: it parses to itself.
- parameter string: String to parse.
- returns: `string` parameter value.
*/
public static func parse(_ string: String) -> String? {
return string
}
}
// MARK: - Library root class
/**
RAMReel
--
Reel class
*/
open class RAMReel
<
CellClass: UICollectionViewCell,
TextFieldClass: UITextField,
DataSource: FlowDataSource>
where
CellClass: ConfigurableCell,
CellClass.DataType == DataSource.ResultType,
DataSource.QueryType == String,
DataSource.ResultType: Renderable,
DataSource.ResultType: Parsable
{
/// Container view
public let view: UIView
/// Gradient View
let gradientView: GradientView
// MARK: TextField
let reactor: TextFieldReactor<DataSource, CollectionWrapperClass>
let textField: TextFieldClass
let returnTarget: TextFieldTarget
private var untouchedTarget : TextFieldTarget? = nil
let gestureTarget: GestureTarget
let dataFlow: DataFlow<DataSource, CollectionViewWrapper<CellClass.DataType, CellClass>>
/// Delegate of text field, is used for extra control over text field.
open var textFieldDelegate: UITextFieldDelegate? {
set { textField.delegate = newValue }
get { return textField.delegate }
}
/// Use this method when you want textField release input focus.
open func resignFirstResponder() {
self.textField.resignFirstResponder()
}
// MARK: CollectionView
typealias CollectionWrapperClass = CollectionViewWrapper<DataSource.ResultType, CellClass>
let wrapper: CollectionWrapperClass
/// Collection view with data items.
public let collectionView: UICollectionView
// MARK: Data Source
/// Data source of RAMReel
public let dataSource: DataSource
// MARK: Selected Item
/**
Use this property to get which item was selected.
Value is nil, if data source output is empty.
*/
open var selectedItem: DataSource.ResultType? {
return textField.text.flatMap(DataSource.ResultType.parse)
}
// MARK: Hooks
/**
Type of selected item change callback hook
*/
public typealias HookType = (DataSource.ResultType) -> ()
/// This hooks that are called on selected item change
open var hooks: [HookType] = []
// MARK: Layout
let layout: UICollectionViewLayout = RAMCollectionViewLayout()
// MARK: Theme
/// Visual appearance theme
open var theme: Theme = RAMTheme.sharedTheme {
didSet {
guard theme.font != oldValue.font
||
theme.listBackgroundColor != oldValue.listBackgroundColor
||
theme.textColor != oldValue.textColor
else {
return
}
updateVisuals()
updatePlaceholder(self.placeholder)
}
}
fileprivate func updateVisuals() {
self.view.tintColor = theme.textColor
self.textField.font = theme.font
self.textField.textColor = theme.textColor
(self.textField as UITextField).tintColor = theme.textColor
self.textField.keyboardAppearance = UIKeyboardAppearance.dark
self.gradientView.listBackgroundColor = theme.listBackgroundColor
self.view.layer.mask = self.gradientView.layer
self.view.backgroundColor = UIColor.clear
self.collectionView.backgroundColor = theme.listBackgroundColor
self.collectionView.showsHorizontalScrollIndicator = false
self.collectionView.showsVerticalScrollIndicator = false
self.textField.autocapitalizationType = UITextAutocapitalizationType.none
self.textField.autocorrectionType = UITextAutocorrectionType.no
self.textField.clearButtonMode = UITextField.ViewMode.whileEditing
self.updatePlaceholder(self.placeholder)
self.wrapper.theme = self.theme
let visibleCells: [CellClass] = self.collectionView.visibleCells as! [CellClass]
visibleCells.forEach { (cell: CellClass) -> Void in
var cell = cell
cell.theme = self.theme
}
}
/// Placeholder in text field.
open var placeholder: String = "" {
willSet {
updatePlaceholder(newValue)
}
}
fileprivate func updatePlaceholder(_ placeholder:String) {
let themeFont = self.theme.font
let size = self.textField.textRect(forBounds: textField.bounds).height * themeFont.pointSize / themeFont.lineHeight * 0.8
let font = (size > 0) ? (UIFont(name: themeFont.fontName, size: size) ?? themeFont) : themeFont
self.textField.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [
NSAttributedString.Key.font: font,
NSAttributedString.Key.foregroundColor: self.theme.textColor.withAlphaComponent(0.5)
])
}
var bottomConstraints: [NSLayoutConstraint] = []
let keyboardCallbackWrapper: NotificationCallbackWrapper
let attemptToDodgeKeyboard : Bool
// MARK: Initialization
/**
Creates new `RAMReel` instance.
- parameters:
- frame: Rect that Reel will occupy
- dataSource: Object of type that implements FlowDataSource protocol
- placeholder: Optional text field placeholder
- hook: Optional initial value change hook
- attemptToDodgeKeyboard: attempt to center the widget on the available screen area when the iOS
keyboard appears (will cause issues if the widget isn't being used in full screen)
*/
public init(frame: CGRect, dataSource: DataSource, placeholder: String = "", attemptToDodgeKeyboard: Bool, hook: HookType? = nil) {
self.view = UIView(frame: frame)
self.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.view.translatesAutoresizingMaskIntoConstraints = true
self.dataSource = dataSource
self.attemptToDodgeKeyboard = attemptToDodgeKeyboard
if let h = hook {
self.hooks.append(h)
}
// MARK: CollectionView
self.collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: layout)
self.collectionView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(self.collectionView)
self.wrapper = CollectionViewWrapper(collectionView: collectionView, theme: self.theme)
// MARK: TextField
self.textField = TextFieldClass()
self.textField.returnKeyType = UIReturnKeyType.done
self.textField.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(self.textField)
self.placeholder = placeholder
dataFlow = dataSource *> wrapper
reactor = textField <&> dataFlow
self.gradientView = GradientView(frame: view.bounds)
self.gradientView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
self.gradientView.translatesAutoresizingMaskIntoConstraints = true
self.view.insertSubview(self.gradientView, at: 0)
views = [
"collectionView": collectionView,
"textField": textField
]
self.keyboardCallbackWrapper = NotificationCallbackWrapper(name: UIResponder.keyboardWillChangeFrameNotification.rawValue)
returnTarget = TextFieldTarget()
gestureTarget = GestureTarget()
let controlEvents = UIControl.Event.editingDidEndOnExit
returnTarget.beTargetFor(textField, controlEvents: controlEvents) { [weak self] textField -> () in
guard let `self` = self else { return }
if
let text = textField.text,
let item = DataSource.ResultType.parse(text)
{
for hook in self.hooks {
hook(item)
}
self.wrapper.data = []
}
}
gestureTarget.recognizeFor(collectionView, type: GestureTarget.GestureType.tap) { [weak self] _, _ in
if
let `self` = self,
let selectedItem = self.wrapper.selectedItem
{
self.textField.becomeFirstResponder()
self.textField.text = nil
self.textField.insertText(selectedItem.render())
}
}
gestureTarget.recognizeFor(collectionView, type: GestureTarget.GestureType.swipe) { _,_ in }
weak var s = self
self.untouchedTarget = TextFieldTarget(controlEvents: UIControl.Event.editingChanged, textField: self.textField, hook: {_ in s?.placeholder = "";})
self.keyboardCallbackWrapper.callback = { [weak self] notification in
guard let `self` = self else { return }
if let userInfo = (notification as NSNotification).userInfo as! [String: AnyObject]?,
let endFrame = userInfo[UIResponder.keyboardFrameEndUserInfoKey]?.cgRectValue,
let animDuration: TimeInterval = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey]?.doubleValue,
let animCurveRaw = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey]?.uintValue {
if (attemptToDodgeKeyboard) {
let animCurve = UIView.AnimationOptions(rawValue: UInt(animCurveRaw))
for bottomConstraint in self.bottomConstraints {
bottomConstraint.constant = self.view.frame.height - endFrame.origin.y
}
UIView.animate(withDuration: animDuration,
delay: 0.0,
options: animCurve,
animations: {
self.gradientView.layer.frame.size.height = endFrame.origin.y
self.textField.layoutIfNeeded()
}, completion: nil)
}
}
}
updateVisuals()
addHConstraints()
addVConstraints()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
/// Call this method to update `RAMReel` visuals before showing it.
open func prepareForViewing() {
updateVisuals()
updatePlaceholder(self.placeholder)
}
/// If you use `RAMReel` to enter a set of values from the list call this method before each input.
open func prepareForReuse() {
self.textField.text = ""
self.dataFlow.transport("")
}
// MARK: Constraints
fileprivate let views: [String: UIView]
func addHConstraints() {
// Horisontal constraints
let collectionHConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|[collectionView]|", options: NSLayoutConstraint.FormatOptions.alignAllCenterX, metrics: nil, views: views)
view.addConstraints(collectionHConstraints)
let textFieldHConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(20)-[textField]-(20)-|", options: NSLayoutConstraint.FormatOptions.alignAllCenterX, metrics: nil, views: views)
view.addConstraints(textFieldHConstraints)
}
func addVConstraints() {
// Vertical constraints
let collectionVConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|[collectionView]|", options: NSLayoutConstraint.FormatOptions.alignAllCenterY, metrics: nil, views: views)
view.addConstraints(collectionVConstraints)
if let bottomConstraint = collectionVConstraints.filter({ $0.firstAttribute == NSLayoutConstraint.Attribute.bottom }).first {
bottomConstraints.append(bottomConstraint)
}
let textFieldVConstraints = [NSLayoutConstraint(item: textField, attribute: NSLayoutConstraint.Attribute.centerY, relatedBy: NSLayoutConstraint.Relation.equal, toItem: collectionView, attribute: NSLayoutConstraint.Attribute.centerY, multiplier: 1.0, constant: 0.0)] + NSLayoutConstraint.constraints(withVisualFormat: "V:[textField(>=44)]", options: NSLayoutConstraint.FormatOptions.alignAllCenterY, metrics: nil, views: views)
view.addConstraints(textFieldVConstraints)
}
}
// MARK: - Helpers
class NotificationCallbackWrapper: NSObject {
@objc func callItBack(_ notification: Notification) {
callback?(notification)
}
typealias NotificationToVoid = (Notification) -> ()
var callback: NotificationToVoid?
init(name: String, object: AnyObject? = nil) {
super.init()
NotificationCenter.default.addObserver(
self,
selector: #selector(NotificationCallbackWrapper.callItBack(_:)),
name: NSNotification.Name(rawValue: name),
object: object
)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
final class GestureTarget: NSObject, UIGestureRecognizerDelegate {
static let gestureSelector = #selector(GestureTarget.gesture(_:))
override init() {
super.init()
}
init(type: GestureType, view: UIView, hook: @escaping HookType) {
super.init()
recognizeFor(view, type: type, hook: hook)
}
typealias HookType = (UIView, UIGestureRecognizer) -> ()
enum GestureType {
case tap
case longPress
case swipe
}
var hooks: [UIGestureRecognizer: (UIView, HookType)] = [:]
func recognizeFor(_ view: UIView, type: GestureType, hook: @escaping HookType) {
let gestureRecognizer: UIGestureRecognizer
switch type {
case .tap:
gestureRecognizer = UITapGestureRecognizer(target: self, action: GestureTarget.gestureSelector)
case .longPress:
gestureRecognizer = UILongPressGestureRecognizer(target: self, action: GestureTarget.gestureSelector)
case .swipe:
gestureRecognizer = UISwipeGestureRecognizer(target: self, action: GestureTarget.gestureSelector)
}
gestureRecognizer.delegate = self
view.addGestureRecognizer(gestureRecognizer)
let item: (UIView, HookType) = (view, hook)
hooks[gestureRecognizer] = item
}
deinit {
for (recognizer, (view, _)) in hooks {
view.removeGestureRecognizer(recognizer)
}
}
@objc func gesture(_ gestureRecognizer: UIGestureRecognizer) {
if let (textField, hook) = hooks[gestureRecognizer] {
hook(textField, gestureRecognizer)
}
}
// Gesture recognizer delegate
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRequireFailureOf otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}