-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Copy pathSettingsTableViewController.swift
780 lines (650 loc) · 29.7 KB
/
SettingsTableViewController.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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Account
import Shared
import UIKit
struct SettingsUX {
static let TableViewHeaderBackgroundColor = UIConstants.AppBackgroundColor
static let TableViewHeaderTextColor = UIColor.Photon.Grey50
static let TableViewRowTextColor = UIColor.Photon.Grey90
static let TableViewDisabledRowTextColor = UIColor.lightGray
static let TableViewSeparatorColor = UIColor(rgb: 0xD1D1D4)
static let TableViewHeaderFooterHeight = CGFloat(44)
static let TableViewRowErrorTextColor = UIColor(red: 255/255, green: 0/255, blue: 26/255, alpha: 1.0)
static let TableViewRowWarningTextColor = UIColor(red: 245/255, green: 166/255, blue: 35/255, alpha: 1.0)
static let TableViewRowActionAccessoryColor = UIColor(red: 0.29, green: 0.56, blue: 0.89, alpha: 1.0)
static let TableViewRowSyncTextColor = UIColor(red: 51/255, green: 51/255, blue: 51/255, alpha: 1.0)
}
// A base setting class that shows a title. You probably want to subclass this, not use it directly.
class Setting: NSObject {
fileprivate var _title: NSAttributedString?
fileprivate var _footerTitle: NSAttributedString?
fileprivate var _cellHeight: CGFloat?
fileprivate var _image: UIImage?
weak var delegate: SettingsDelegate?
// The url the SettingsContentViewController will show, e.g. Licenses and Privacy Policy.
var url: URL? { return nil }
// The title shown on the pref.
var title: NSAttributedString? { return _title }
var footerTitle: NSAttributedString? { return _footerTitle }
var cellHeight: CGFloat? { return _cellHeight}
fileprivate(set) var accessibilityIdentifier: String?
// An optional second line of text shown on the pref.
var status: NSAttributedString? { return nil }
// Whether or not to show this pref.
var hidden: Bool { return false }
var style: UITableViewCellStyle { return .subtitle }
var accessoryType: UITableViewCellAccessoryType { return .none }
var textAlignment: NSTextAlignment { return .natural }
var image: UIImage? { return _image }
fileprivate(set) var enabled: Bool = true
// Called when the cell is setup. Call if you need the default behaviour.
func onConfigureCell(_ cell: UITableViewCell) {
cell.detailTextLabel?.attributedText = status
cell.detailTextLabel?.numberOfLines = 0
cell.textLabel?.attributedText = title
cell.textLabel?.textAlignment = textAlignment
cell.textLabel?.numberOfLines = 1
cell.textLabel?.lineBreakMode = .byTruncatingTail
cell.accessoryType = accessoryType
cell.accessoryView = nil
cell.selectionStyle = enabled ? .default : .none
cell.accessibilityIdentifier = accessibilityIdentifier
cell.imageView?.image = _image
if let title = title?.string {
if let detailText = cell.detailTextLabel?.text {
cell.accessibilityLabel = "\(title), \(detailText)"
} else if let status = status?.string {
cell.accessibilityLabel = "\(title), \(status)"
} else {
cell.accessibilityLabel = title
}
}
cell.accessibilityTraits = UIAccessibilityTraitButton
cell.indentationWidth = 0
cell.layoutMargins = .zero
// So that the separator line goes all the way to the left edge.
cell.separatorInset = .zero
}
// Called when the pref is tapped.
func onClick(_ navigationController: UINavigationController?) { return }
// Helper method to set up and push a SettingsContentViewController
func setUpAndPushSettingsContentViewController(_ navigationController: UINavigationController?) {
if let url = self.url {
let viewController = SettingsContentViewController()
viewController.settingsTitle = self.title
viewController.url = url
navigationController?.pushViewController(viewController, animated: true)
}
}
init(title: NSAttributedString? = nil, footerTitle: NSAttributedString? = nil, cellHeight: CGFloat? = nil, delegate: SettingsDelegate? = nil, enabled: Bool? = nil) {
self._title = title
self._footerTitle = footerTitle
self._cellHeight = cellHeight
self.delegate = delegate
self.enabled = enabled ?? true
}
}
// A setting in the sections panel. Contains a sublist of Settings
class SettingSection: Setting {
fileprivate let children: [Setting]
init(title: NSAttributedString? = nil, footerTitle: NSAttributedString? = nil, cellHeight: CGFloat? = nil, children: [Setting]) {
self.children = children
super.init(title: title, footerTitle: footerTitle, cellHeight: cellHeight)
}
var count: Int {
var count = 0
for setting in children where !setting.hidden {
count += 1
}
return count
}
subscript(val: Int) -> Setting? {
var i = 0
for setting in children where !setting.hidden {
if i == val {
return setting
}
i += 1
}
return nil
}
}
private class PaddedSwitch: UIView {
fileprivate static let Padding: CGFloat = 8
init(switchView: UISwitch) {
super.init(frame: .zero)
addSubview(switchView)
frame.size = CGSize(width: switchView.frame.width + PaddedSwitch.Padding, height: switchView.frame.height)
switchView.frame.origin = CGPoint(x: PaddedSwitch.Padding, y: 0)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// A helper class for settings with a UISwitch.
// Takes and optional settingsDidChange callback and status text.
class BoolSetting: Setting {
let prefKey: String? // Sometimes a subclass will manage its own pref setting. In that case the prefkey will be nil
fileprivate let prefs: Prefs
fileprivate let defaultValue: Bool
fileprivate let settingDidChange: ((Bool) -> Void)?
fileprivate let statusText: NSAttributedString?
init(prefs: Prefs, prefKey: String? = nil, defaultValue: Bool, attributedTitleText: NSAttributedString, attributedStatusText: NSAttributedString? = nil, settingDidChange: ((Bool) -> Void)? = nil) {
self.prefs = prefs
self.prefKey = prefKey
self.defaultValue = defaultValue
self.settingDidChange = settingDidChange
self.statusText = attributedStatusText
super.init(title: attributedTitleText)
}
convenience init(prefs: Prefs, prefKey: String? = nil, defaultValue: Bool, titleText: String, statusText: String? = nil, settingDidChange: ((Bool) -> Void)? = nil) {
var statusTextAttributedString: NSAttributedString?
if let statusTextString = statusText {
statusTextAttributedString = NSAttributedString(string: statusTextString, attributes: [NSAttributedStringKey.foregroundColor: SettingsUX.TableViewHeaderTextColor])
}
self.init(prefs: prefs, prefKey: prefKey, defaultValue: defaultValue, attributedTitleText: NSAttributedString(string: titleText, attributes: [NSAttributedStringKey.foregroundColor: SettingsUX.TableViewRowTextColor]), attributedStatusText: statusTextAttributedString, settingDidChange: settingDidChange)
}
override var status: NSAttributedString? {
return statusText
}
override func onConfigureCell(_ cell: UITableViewCell) {
super.onConfigureCell(cell)
let control = UISwitch()
control.onTintColor = UIConstants.SystemBlueColor
control.addTarget(self, action: #selector(switchValueChanged), for: .valueChanged)
control.accessibilityIdentifier = prefKey
displayBool(control)
if let title = title {
if let status = status {
control.accessibilityLabel = "\(title.string), \(status.string)"
} else {
control.accessibilityLabel = title.string
}
cell.accessibilityLabel = nil
}
cell.accessoryView = PaddedSwitch(switchView: control)
cell.selectionStyle = .none
}
@objc func switchValueChanged(_ control: UISwitch) {
writeBool(control)
settingDidChange?(control.isOn)
UnifiedTelemetry.recordEvent(category: .action, method: .change, object: .setting, value: self.prefKey, extras: ["to": control.isOn])
}
// These methods allow a subclass to control how the pref is saved
func displayBool(_ control: UISwitch) {
guard let key = prefKey else {
return
}
control.isOn = prefs.boolForKey(key) ?? defaultValue
}
func writeBool(_ control: UISwitch) {
guard let key = prefKey else {
return
}
prefs.setBool(control.isOn, forKey: key)
}
}
class PrefPersister: SettingValuePersister {
fileprivate let prefs: Prefs
let prefKey: String
init(prefs: Prefs, prefKey: String) {
self.prefs = prefs
self.prefKey = prefKey
}
func readPersistedValue() -> String? {
return prefs.stringForKey(prefKey)
}
func writePersistedValue(value: String?) {
if let value = value {
prefs.setString(value, forKey: prefKey)
} else {
prefs.removeObjectForKey(prefKey)
}
}
}
class StringPrefSetting: StringSetting {
init(prefs: Prefs, prefKey: String, defaultValue: String? = nil, placeholder: String, accessibilityIdentifier: String, settingIsValid isValueValid: ((String?) -> Bool)? = nil, settingDidChange: ((String?) -> Void)? = nil) {
super.init(defaultValue: defaultValue, placeholder: placeholder, accessibilityIdentifier: accessibilityIdentifier, persister: PrefPersister(prefs: prefs, prefKey: prefKey), settingIsValid: isValueValid, settingDidChange: settingDidChange)
}
}
protocol SettingValuePersister {
func readPersistedValue() -> String?
func writePersistedValue(value: String?)
}
/// A helper class for a setting backed by a UITextField.
/// This takes an optional settingIsValid and settingDidChange callback
/// If settingIsValid returns false, the Setting will not change and the text remains red.
class StringSetting: Setting, UITextFieldDelegate {
var Padding: CGFloat = 8
fileprivate let defaultValue: String?
fileprivate let placeholder: String
fileprivate let settingDidChange: ((String?) -> Void)?
fileprivate let settingIsValid: ((String?) -> Bool)?
fileprivate let persister: SettingValuePersister
let textField = UITextField()
init(defaultValue: String? = nil, placeholder: String, accessibilityIdentifier: String, persister: SettingValuePersister, settingIsValid isValueValid: ((String?) -> Bool)? = nil, settingDidChange: ((String?) -> Void)? = nil) {
self.defaultValue = defaultValue
self.settingDidChange = settingDidChange
self.settingIsValid = isValueValid
self.placeholder = placeholder
self.persister = persister
super.init()
self.accessibilityIdentifier = accessibilityIdentifier
}
override func onConfigureCell(_ cell: UITableViewCell) {
super.onConfigureCell(cell)
if let id = accessibilityIdentifier {
textField.accessibilityIdentifier = id + "TextField"
}
textField.placeholder = placeholder
textField.textAlignment = .center
textField.delegate = self
textField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
cell.isUserInteractionEnabled = true
cell.accessibilityTraits = UIAccessibilityTraitNone
cell.contentView.addSubview(textField)
textField.snp.makeConstraints { make in
make.height.equalTo(44)
make.trailing.equalTo(cell.contentView).offset(-Padding)
make.leading.equalTo(cell.contentView).offset(Padding)
}
textField.text = self.persister.readPersistedValue() ?? defaultValue
textFieldDidChange(textField)
}
override func onClick(_ navigationController: UINavigationController?) {
textField.becomeFirstResponder()
}
fileprivate func isValid(_ value: String?) -> Bool {
guard let test = settingIsValid else {
return true
}
return test(prepareValidValue(userInput: value))
}
/// This gives subclasses an opportunity to treat the user input string
/// before it is saved or tested.
/// Default implementation does nothing.
func prepareValidValue(userInput value: String?) -> String? {
return value
}
@objc func textFieldDidChange(_ textField: UITextField) {
let color = isValid(textField.text) ? SettingsUX.TableViewRowTextColor : UIConstants.DestructiveRed
textField.textColor = color
}
@objc func textFieldShouldReturn(_ textField: UITextField) -> Bool {
return isValid(textField.text)
}
@objc func textFieldDidEndEditing(_ textField: UITextField) {
let text = textField.text
if !isValid(text) {
return
}
self.persister.writePersistedValue(value: prepareValidValue(userInput: text))
// Call settingDidChange with text or nil.
settingDidChange?(text)
}
}
class CheckmarkSetting: Setting {
let onChanged: () -> Void
let isEnabled: () -> Bool
private let subtitle: NSAttributedString?
override var status: NSAttributedString? {
return subtitle
}
init(title: NSAttributedString, subtitle: NSAttributedString?, accessibilityIdentifier: String? = nil, isEnabled: @escaping () -> Bool, onChanged: @escaping () -> Void) {
self.subtitle = subtitle
self.onChanged = onChanged
self.isEnabled = isEnabled
super.init(title: title)
self.accessibilityIdentifier = accessibilityIdentifier
}
override func onConfigureCell(_ cell: UITableViewCell) {
super.onConfigureCell(cell)
cell.accessoryType = isEnabled() ? .checkmark : .none
cell.selectionStyle = .none
}
override func onClick(_ navigationController: UINavigationController?) {
// Force editing to end for any focused text fields so they can finish up validation first.
navigationController?.view.endEditing(true)
if !isEnabled() {
onChanged()
}
}
}
/// A helper class for a setting backed by a UITextField.
/// This takes an optional isEnabled and mandatory onClick callback
/// isEnabled is called on each tableview.reloadData. If it returns
/// false then the 'button' appears disabled.
class ButtonSetting: Setting {
let onButtonClick: (UINavigationController?) -> Void
let destructive: Bool
let isEnabled: (() -> Bool)?
init(title: NSAttributedString?, destructive: Bool = false, accessibilityIdentifier: String, isEnabled: (() -> Bool)? = nil, onClick: @escaping (UINavigationController?) -> Void) {
self.onButtonClick = onClick
self.destructive = destructive
self.isEnabled = isEnabled
super.init(title: title)
self.accessibilityIdentifier = accessibilityIdentifier
}
override func onConfigureCell(_ cell: UITableViewCell) {
super.onConfigureCell(cell)
if isEnabled?() ?? true {
cell.textLabel?.textColor = destructive ? UIConstants.DestructiveRed : UIConstants.HighlightBlue
} else {
cell.textLabel?.textColor = SettingsUX.TableViewDisabledRowTextColor
}
cell.textLabel?.textAlignment = .center
cell.accessibilityTraits = UIAccessibilityTraitButton
cell.selectionStyle = .none
}
override func onClick(_ navigationController: UINavigationController?) {
// Force editing to end for any focused text fields so they can finish up validation first.
navigationController?.view.endEditing(true)
if isEnabled?() ?? true {
onButtonClick(navigationController)
}
}
}
// A helper class for prefs that deal with sync. Handles reloading the tableView data if changes to
// the fxAccount happen.
class AccountSetting: Setting, FxAContentViewControllerDelegate {
unowned var settings: SettingsTableViewController
var profile: Profile {
return settings.profile
}
override var title: NSAttributedString? { return nil }
init(settings: SettingsTableViewController) {
self.settings = settings
super.init(title: nil)
}
override func onConfigureCell(_ cell: UITableViewCell) {
super.onConfigureCell(cell)
if settings.profile.getAccount() != nil {
cell.selectionStyle = .none
}
}
override var accessoryType: UITableViewCellAccessoryType { return .none }
func contentViewControllerDidSignIn(_ viewController: FxAContentViewController, withFlags flags: FxALoginFlags) {
// This method will get called twice: once when the user signs in, and once
// when the account is verified by email – on this device or another.
// If the user hasn't dismissed the fxa content view controller,
// then we should only do that (thus finishing the sign in/verification process)
// once the account is verified.
// By the time we get to here, we should be syncing or just about to sync in the
// background, most likely from FxALoginHelper.
if flags.verified {
_ = settings.navigationController?.popToRootViewController(animated: true)
// Reload the data to reflect the new Account immediately.
settings.tableView.reloadData()
// And start advancing the Account state in the background as well.
settings.refresh()
}
}
func contentViewControllerDidCancel(_ viewController: FxAContentViewController) {
NSLog("didCancel")
_ = settings.navigationController?.popToRootViewController(animated: true)
}
}
class WithAccountSetting: AccountSetting {
override var hidden: Bool { return !profile.hasAccount() }
}
class WithoutAccountSetting: AccountSetting {
override var hidden: Bool { return profile.hasAccount() }
}
@objc
protocol SettingsDelegate: class {
func settingsOpenURLInNewTab(_ url: URL)
}
// The base settings view controller.
class SettingsTableViewController: UITableViewController {
typealias SettingsGenerator = (SettingsTableViewController, SettingsDelegate?) -> [SettingSection]
fileprivate let Identifier = "CellIdentifier"
fileprivate let SectionHeaderIdentifier = "SectionHeaderIdentifier"
var settings = [SettingSection]()
weak var settingsDelegate: SettingsDelegate?
var profile: Profile!
var tabManager: TabManager!
var hasSectionSeparatorLine = true
/// Used to calculate cell heights.
fileprivate lazy var dummyToggleCell: UITableViewCell = {
let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "dummyCell")
cell.accessoryView = UISwitch()
return cell
}()
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: Identifier)
tableView.register(SettingsTableSectionHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: SectionHeaderIdentifier)
tableView.separatorColor = SettingsUX.TableViewSeparatorColor
tableView.backgroundColor = SettingsUX.TableViewHeaderBackgroundColor
tableView.tableFooterView = UIView(frame: CGRect(width: view.frame.width, height: 30))
tableView.estimatedRowHeight = 44
tableView.estimatedSectionHeaderHeight = 44
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
settings = generateSettings()
NotificationCenter.default.addObserver(self, selector: #selector(syncDidChangeState), name: .ProfileDidStartSyncing, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(syncDidChangeState), name: .ProfileDidFinishSyncing, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(firefoxAccountDidChange), name: .FirefoxAccountChanged, object: nil)
tableView.reloadData()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
refresh()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
[Notification.Name.ProfileDidStartSyncing, Notification.Name.ProfileDidFinishSyncing, Notification.Name.FirefoxAccountChanged].forEach { name in
NotificationCenter.default.removeObserver(self, name: name, object: nil)
}
}
// Override to provide settings in subclasses
func generateSettings() -> [SettingSection] {
return []
}
@objc fileprivate func syncDidChangeState() {
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
@objc fileprivate func refresh() {
// Through-out, be aware that modifying the control while a refresh is in progress is /not/ supported and will likely crash the app.
if let account = self.profile.getAccount() {
account.advance().upon { state in
DispatchQueue.main.async { () -> Void in
self.tableView.reloadData()
}
}
} else {
self.tableView.reloadData()
}
}
@objc func firefoxAccountDidChange() {
self.tableView.reloadData()
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let section = settings[indexPath.section]
if let setting = section[indexPath.row] {
var cell: UITableViewCell!
if let _ = setting.status {
// Work around http://stackoverflow.com/a/9999821 and http://stackoverflow.com/a/25901083 by using a new cell.
// I could not make any setNeedsLayout solution work in the case where we disconnect and then connect a new account.
// Be aware that dequeing and then ignoring a cell appears to cause issues; only deque a cell if you're going to return it.
cell = UITableViewCell(style: setting.style, reuseIdentifier: nil)
} else {
cell = tableView.dequeueReusableCell(withIdentifier: Identifier, for: indexPath)
}
setting.onConfigureCell(cell)
return cell
}
return tableView.dequeueReusableCell(withIdentifier: Identifier, for: indexPath)
}
override func numberOfSections(in tableView: UITableView) -> Int {
return settings.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let section = settings[section]
return section.count
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: SectionHeaderIdentifier) as! SettingsTableSectionHeaderFooterView
let sectionSetting = settings[section]
if let sectionTitle = sectionSetting.title?.string {
headerView.titleLabel.text = sectionTitle.uppercased()
}
// Hide the top border for the top section to avoid having a double line at the top
if section == 0 || !hasSectionSeparatorLine {
headerView.showTopBorder = false
} else {
headerView.showTopBorder = true
}
return headerView
}
override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let sectionSetting = settings[section]
guard let sectionFooter = sectionSetting.footerTitle?.string else {
return nil
}
let footerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: SectionHeaderIdentifier) as! SettingsTableSectionHeaderFooterView
footerView.titleLabel.text = sectionFooter
footerView.titleAlignment = .top
footerView.showBottomBorder = false
return footerView
}
// To hide a footer dynamically requires returning nil from viewForFooterInSection
// and setting the height to zero.
// However, we also want the height dynamically calculated, there is a magic constant
// for that: `UITableViewAutomaticDimension`.
override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
let sectionSetting = settings[section]
if let _ = sectionSetting.footerTitle?.string {
return UITableViewAutomaticDimension
}
return 0
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let section = settings[indexPath.section]
// Workaround for calculating the height of default UITableViewCell cells with a subtitle under
// the title text label.
if let setting = section[indexPath.row], setting is BoolSetting && setting.status != nil {
return calculateStatusCellHeightForSetting(setting)
}
if let setting = section[indexPath.row], let height = setting.cellHeight {
return height
}
return UITableViewAutomaticDimension
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let section = settings[indexPath.section]
if let setting = section[indexPath.row], setting.enabled {
setting.onClick(navigationController)
}
}
fileprivate func calculateStatusCellHeightForSetting(_ setting: Setting) -> CGFloat {
dummyToggleCell.layoutSubviews()
let topBottomMargin: CGFloat = 10
let width = dummyToggleCell.contentView.frame.width - 2 * dummyToggleCell.separatorInset.left
return
heightForLabel(dummyToggleCell.textLabel!, width: width, text: setting.title?.string) +
heightForLabel(dummyToggleCell.detailTextLabel!, width: width, text: setting.status?.string) +
2 * topBottomMargin
}
fileprivate func heightForLabel(_ label: UILabel, width: CGFloat, text: String?) -> CGFloat {
guard let text = text else { return 0 }
let size = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)
let attrs = [NSAttributedStringKey.font: label.font as Any]
let boundingRect = NSString(string: text).boundingRect(with: size,
options: .usesLineFragmentOrigin, attributes: attrs, context: nil)
return boundingRect.height
}
}
private struct SettingsTableSectionHeaderFooterViewUX {
static let titleHorizontalPadding: CGFloat = 15
static let titleVerticalPadding: CGFloat = 6
static let titleVerticalLongPadding: CGFloat = 20
}
class SettingsTableSectionHeaderFooterView: UITableViewHeaderFooterView {
enum TitleAlignment {
case top
case bottom
}
var titleAlignment: TitleAlignment = .bottom {
didSet {
remakeTitleAlignmentConstraints()
}
}
var showTopBorder: Bool = true {
didSet {
topBorder.isHidden = !showTopBorder
}
}
var showBottomBorder: Bool = true {
didSet {
bottomBorder.isHidden = !showBottomBorder
}
}
lazy var titleLabel: UILabel = {
var headerLabel = UILabel()
headerLabel.textColor = SettingsUX.TableViewHeaderTextColor
headerLabel.font = UIFont.systemFont(ofSize: 12.0, weight: UIFont.Weight.regular)
headerLabel.numberOfLines = 0
return headerLabel
}()
fileprivate lazy var topBorder: UIView = {
let topBorder = UIView()
topBorder.backgroundColor = UIConstants.SeparatorColor
return topBorder
}()
fileprivate lazy var bottomBorder: UIView = {
let bottomBorder = UIView()
bottomBorder.backgroundColor = UIConstants.SeparatorColor
return bottomBorder
}()
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
contentView.backgroundColor = SettingsUX.TableViewHeaderBackgroundColor
addSubview(titleLabel)
addSubview(topBorder)
addSubview(bottomBorder)
setupInitialConstraints()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupInitialConstraints() {
bottomBorder.snp.makeConstraints { make in
make.bottom.left.right.equalTo(self)
make.height.equalTo(0.5)
}
topBorder.snp.makeConstraints { make in
make.top.left.right.equalTo(self)
make.height.equalTo(0.5)
}
remakeTitleAlignmentConstraints()
}
override func prepareForReuse() {
super.prepareForReuse()
showTopBorder = true
showBottomBorder = true
titleLabel.text = nil
titleAlignment = .bottom
}
fileprivate func remakeTitleAlignmentConstraints() {
switch titleAlignment {
case .top:
titleLabel.snp.remakeConstraints { make in
make.left.right.equalTo(self).inset(SettingsTableSectionHeaderFooterViewUX.titleHorizontalPadding)
make.top.equalTo(self).offset(SettingsTableSectionHeaderFooterViewUX.titleVerticalPadding)
make.bottom.equalTo(self).offset(-SettingsTableSectionHeaderFooterViewUX.titleVerticalLongPadding)
}
case .bottom:
titleLabel.snp.remakeConstraints { make in
make.left.right.equalTo(self).inset(SettingsTableSectionHeaderFooterViewUX.titleHorizontalPadding)
make.bottom.equalTo(self).offset(-SettingsTableSectionHeaderFooterViewUX.titleVerticalPadding)
make.top.equalTo(self).offset(SettingsTableSectionHeaderFooterViewUX.titleVerticalLongPadding)
}
}
}
}