-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathMultiPickerDialog.swift
352 lines (269 loc) · 14.8 KB
/
MultiPickerDialog.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
//
// MultiPickerDialog.swift
//
// Created by Mohamed Badi3 on 25/10/2016.
//
import Foundation
import UIKit
import QuartzCore
import ObjectiveC
class MultiPickerDialog: UIView, UITableViewDelegate, UITableViewDataSource {
typealias MultiPickerCallback = (_ values: [[String: String]]) -> Void
/* Constants */
private let kPickerDialogDefaultButtonHeight: CGFloat = 50
private let kPickerDialogDefaultButtonSpacerHeight: CGFloat = 1
private let kPickerDialogCornerRadius: CGFloat = 7
private let kPickerDialogDoneButtonTag: Int = 1
/* Views */
private var dialogView: UIView!
private var titleLabel: UILabel!
private var picker: UITableView!
private var cancelButton: UIButton!
private var doneButton: UIButton!
/* Variables */
private var pickerData = [[String: String]]()
private var selectedPickerValues: [String]?
private var callback: MultiPickerCallback?
/* Overrides */
init() {
super.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height))
setupView()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupView() {
self.dialogView = createContainerView()
self.dialogView!.layer.shouldRasterize = true
self.dialogView!.layer.rasterizationScale = UIScreen.main.scale
self.layer.shouldRasterize = true
self.layer.rasterizationScale = UIScreen.main.scale
self.dialogView!.layer.opacity = 0.5
self.dialogView!.layer.transform = CATransform3DMakeScale(1.3, 1.3, 1)
self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0)
picker.delegate = self
picker.dataSource = self
picker.allowsMultipleSelection = true
/*
NSIndexPath* selectedCellIndexPath= [NSIndexPath indexPathForRow:0 inSection:0];
[self tableView:tableViewList didSelectRowAtIndexPath:selectedCellIndexPath];
[tableViewList selectRowAtIndexPath:selectedCellIndexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
*/
self.addSubview(self.dialogView!)
}
/* Handle device orientation changes */
@objc func deviceOrientationDidChange(notification: NSNotification) {
close() // For now just close it
}
/* Helper to find row of selected value */
func findIndicesForValues(values: [String], array: [[String: String]]) -> [Int] {
var selectedIndices : [Int] = []
for (index, dictionary) in array.enumerated() {
for selectedOption in values {
if dictionary["value"] == selectedOption {
selectedIndices.append(index)
}
}
}
return selectedIndices
}
/* Create the dialog view, and animate opening the dialog */
func show(title: String, doneButtonTitle: String = "Select", cancelButtonTitle: String = "Cancel", options: [[String: String]], selected: [String]? = nil, callback: @escaping MultiPickerCallback) {
self.titleLabel.text = title
self.pickerData = options
self.doneButton.setTitle(doneButtonTitle, for: .normal)
self.cancelButton.setTitle(cancelButtonTitle, for: .normal)
self.callback = callback
if selected != nil {
self.selectedPickerValues = selected
let selectedIndices = findIndicesForValues(values: selected!, array: options)
print("selectedIndices \(selectedIndices)")
for index in selectedIndices{
let selectedCellIndexPath = IndexPath.init(row: index, section: 0)
self.tableView(picker, didSelectRowAt: selectedCellIndexPath)
picker.selectRow(at: selectedCellIndexPath as IndexPath, animated: true, scrollPosition: .none)
}
}
let scene = UIApplication.shared.connectedScenes.first
guard let sceneDelegate = scene?.delegate as? SceneDelegate else{
return
}
sceneDelegate.window?.addSubview(self)
sceneDelegate.window?.bringSubviewToFront(self)
sceneDelegate.window?.endEditing(true)
NotificationCenter.default.addObserver(self, selector: #selector(MultiPickerDialog.deviceOrientationDidChange(notification:)), name: UIDevice.orientationDidChangeNotification, object: nil)
/* Anim */
UIView.animate(
withDuration: 0.2,
delay: 0,
options: UIView.AnimationOptions.curveEaseInOut,
animations: { () -> Void in
self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.4)
self.dialogView!.layer.opacity = 1
self.dialogView!.layer.transform = CATransform3DMakeScale(1, 1, 1)
},
completion: nil
)
}
/* Dialog close animation then cleaning and removing the view from the parent */
private func close() {
NotificationCenter.default.removeObserver(self)
let currentTransform = self.dialogView.layer.transform
let startRotation = (self.value(forKeyPath: "layer.transform.rotation.z") as? NSNumber) as? Double ?? 0.0
let rotation = CATransform3DMakeRotation((CGFloat)(-startRotation + Double.pi * 270 / 180), 0, 0, 0)
self.dialogView.layer.transform = CATransform3DConcat(rotation, CATransform3DMakeScale(1, 1, 1))
self.dialogView.layer.opacity = 1
UIView.animate(
withDuration: 0.2,
delay: 0,
options: [],
animations: { () -> Void in
self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0)
self.dialogView.layer.transform = CATransform3DConcat(currentTransform, CATransform3DMakeScale(0.6, 0.6, 1))
self.dialogView.layer.opacity = 0
}) { (finished: Bool) -> Void in
for v in self.subviews {
v.removeFromSuperview()
}
self.removeFromSuperview()
}
}
/* Creates the container view here: create the dialog, then add the custom content and buttons */
private func createContainerView() -> UIView {
let screenSize = countScreenSize()
let dialogSize = CGSize.init(
width: 300,
height: 230
+ kPickerDialogDefaultButtonHeight
+ kPickerDialogDefaultButtonSpacerHeight)
// For the black background
self.frame = CGRect.init(x: 0, y: 0, width: screenSize.width, height: screenSize.height)
// This is the dialog's container; we attach the custom content and the buttons to this one
let dialogContainer = UIView(frame: CGRect.init(x: (screenSize.width - dialogSize.width) / 2, y: (screenSize.height - dialogSize.height) / 2, width: dialogSize.width, height: dialogSize.height))
// First, we style the dialog to match the iOS8 UIAlertView >>>
let gradient: CAGradientLayer = CAGradientLayer(layer: self.layer)
gradient.frame = dialogContainer.bounds
gradient.colors = [UIColor(red: 218/255, green: 218/255, blue: 218/255, alpha: 1).cgColor,
UIColor(red: 233/255, green: 233/255, blue: 233/255, alpha: 1).cgColor,
UIColor(red: 218/255, green: 218/255, blue: 218/255, alpha: 1).cgColor]
let cornerRadius = kPickerDialogCornerRadius
gradient.cornerRadius = cornerRadius
dialogContainer.layer.insertSublayer(gradient, at: 0)
dialogContainer.layer.cornerRadius = cornerRadius
dialogContainer.layer.borderColor = UIColor(red: 198/255, green: 198/255, blue: 198/255, alpha: 1).cgColor
dialogContainer.layer.borderWidth = 1
dialogContainer.layer.shadowRadius = cornerRadius + 5
dialogContainer.layer.shadowOpacity = 0.1
dialogContainer.layer.shadowOffset = CGSize.init(width: 0 - (cornerRadius + 5) / 2, height: 0 - (cornerRadius + 5) / 2)
dialogContainer.layer.shadowColor = UIColor.black.cgColor
dialogContainer.layer.shadowPath = UIBezierPath(roundedRect: dialogContainer.bounds, cornerRadius: dialogContainer.layer.cornerRadius).cgPath
// There is a line above the button
let lineView = UIView(frame: CGRect.init(x: 0, y: dialogContainer.bounds.size.height - kPickerDialogDefaultButtonHeight - kPickerDialogDefaultButtonSpacerHeight, width: dialogContainer.bounds.size.width, height: kPickerDialogDefaultButtonSpacerHeight))
lineView.backgroundColor = UIColor(red: 198/255, green: 198/255, blue: 198/255, alpha: 1)
dialogContainer.addSubview(lineView)
// ˆˆˆ
//Title
self.titleLabel = UILabel(frame: CGRect.init(x: 10, y: 10, width: 280, height: 30))
self.titleLabel.textAlignment = NSTextAlignment.center
self.titleLabel.textColor = UIColor(hex: 0x333333)
self.titleLabel.font = UIFont(name: "AvenirNext-Medium", size: 18)
dialogContainer.addSubview(self.titleLabel)
self.picker = UITableView(frame: CGRect.init(x: 0, y: 30, width: 10, height: 10))
//self.picker.setValue(UIColor(hex: 0x333333), forKeyPath: "textColor")
self.picker.autoresizingMask = UIView.AutoresizingMask.flexibleRightMargin
self.picker.frame.size.width = 300
self.picker.frame.size.height = 200
self.picker.backgroundColor = UIColor.clear
dialogContainer.addSubview(self.picker)
// Add the buttons
addButtonsToView(container: dialogContainer)
return dialogContainer
}
/* Add buttons to container */
private func addButtonsToView(container: UIView) {
let buttonWidth = container.bounds.size.width / 2
self.cancelButton = UIButton(type: UIButton.ButtonType.custom) as UIButton
self.cancelButton.frame = CGRect.init(x: 0, y: container.bounds.size.height - kPickerDialogDefaultButtonHeight, width: buttonWidth, height: kPickerDialogDefaultButtonHeight)
self.cancelButton.setTitleColor(UIColor(hex: 0x555555), for: .normal)
self.cancelButton.setTitleColor(UIColor(hex: 0x555555), for: .highlighted)
self.cancelButton.titleLabel!.font = UIFont(name: "AvenirNext-Medium", size: 15)
self.cancelButton.layer.cornerRadius = kPickerDialogCornerRadius
self.cancelButton.addTarget(self, action: #selector(MultiPickerDialog.buttonTapped(sender:)), for: UIControl.Event.touchUpInside)
container.addSubview(self.cancelButton)
self.doneButton = UIButton(type: UIButton.ButtonType.custom) as UIButton
self.doneButton.frame = CGRect.init(x: buttonWidth, y: container.bounds.size.height - kPickerDialogDefaultButtonHeight, width: buttonWidth, height: kPickerDialogDefaultButtonHeight)
self.doneButton.tag = kPickerDialogDoneButtonTag
self.doneButton.setTitleColor(UIColor(hex: 0x555555), for: .normal)
self.doneButton.setTitleColor(UIColor(hex: 0x555555), for: .highlighted)
self.doneButton.titleLabel!.font = UIFont(name: "AvenirNext-Medium", size: 15)
self.doneButton.layer.cornerRadius = kPickerDialogCornerRadius
self.doneButton.addTarget(self, action: #selector(MultiPickerDialog.buttonTapped(sender:)), for: .touchUpInside)
container.addSubview(self.doneButton)
}
@objc func buttonTapped(sender: UIButton!) {
if sender.tag == kPickerDialogDoneButtonTag {
var theSelectedValues : [[String: String]] = []
if let indexPathsForSelectedRows = self.picker.indexPathsForSelectedRows{
for indexPath in indexPathsForSelectedRows{
let cell = self.picker.cellForRow(at: indexPath)
theSelectedValues.append(["value":(cell?.contnetIdentifier)!, "display":(cell?.textLabel?.text)!])
}
}
self.callback?(theSelectedValues)
}
close()
}
func countScreenSize() -> CGSize {
return UIScreen.main.bounds.size
}
/* Helper function: count and return the screen's size */
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "cell")
if ((cell == nil)) {
cell = UITableViewCell.init(style: .default, reuseIdentifier: "cell")
}
let theCell = cell!
theCell.textLabel?.text = self.pickerData[indexPath.row]["display"]
theCell.contnetIdentifier = self.pickerData[indexPath.row]["value"]
theCell.textLabel?.textAlignment = .left
theCell.backgroundColor = UIColor.clear
theCell.selectionStyle = .none
let selectedIndexPaths = tableView.indexPathsForSelectedRows
let rowIsSelected = selectedIndexPaths != nil && selectedIndexPaths!.contains(indexPath)
theCell.accessoryType = rowIsSelected ? .checkmark : .none
return theCell
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.pickerData.count
}
internal func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//tableView.cellForRowAtIndexPath(indexPath)?.selected = true
tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
}
internal func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
//tableView.cellForRowAtIndexPath(indexPath)?.selected = false
tableView.cellForRow(at: indexPath)?.accessoryType = UITableViewCell.AccessoryType.none
}
}
var AssociatedObjectHandleOfCellContnetIdentifier: UInt8 = 0
extension UITableViewCell {
var contnetIdentifier:String? {
get {
return objc_getAssociatedObject(self, &AssociatedObjectHandleOfCellContnetIdentifier) as? String
}
set {
objc_setAssociatedObject(self, &AssociatedObjectHandleOfCellContnetIdentifier, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
extension UIColor {
convenience init(hex: Int, alpha: Float = 1.0){
let r = Float((hex >> 16) & 0xFF)
let g = Float((hex >> 8) & 0xFF)
let b = Float((hex) & 0xFF)
self.init(red: CGFloat(r / 255.0), green: CGFloat(g / 255.0), blue:CGFloat(b / 255.0), alpha: CGFloat(alpha))
}
}