Repository navigation
Expand file tree
/
Copy pathOWSTableViewController2.swift
More file actions
1308 lines (1077 loc) · 47.1 KB
/
Copy pathOWSTableViewController2.swift
File metadata and controls
1308 lines (1077 loc) · 47.1 KB
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
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Copyright 2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
//
import SignalServiceKit
// This class offers a convenient way to build table views
// when performance is not critical, e.g. when the table
// only holds a screenful or two of cells and it's safe to
// retain a view model for each cell in memory at all times.
open class OWSTableViewController2: OWSViewController {
public weak var delegate: OWSTableViewControllerDelegate?
public var contents: OWSTableContents {
get {
_contents
}
set {
_contents = newValue
applyContents()
}
}
private var _contents = OWSTableContents()
public func setContents(_ contents: OWSTableContents, shouldReload: Bool = true) {
_contents = contents
applyContents(shouldReload: shouldReload)
}
public let tableView = OWSTableView(frame: .zero, style: .grouped)
// This is an alternative to/replacement for UITableView.tableHeaderView.
//
// * It should usually be used with buildTopHeader(forView:).
// * The top header view appears above the table and _does not_
// scroll with its content.
// * The top header view's edge align with the edges of the cells.
open var topHeader: UIView?
open var bottomFooter: UIView?
public var forceDarkMode = false {
didSet {
applyTheme()
}
}
/// Whether or not this table view should avoid being hidden behind the
/// keyboard.
public var shouldAvoidKeyboard = false
public enum SelectionBehavior {
case actionWithAutoDeselect
case toggleSelectionWithAction
}
public var selectionBehavior: SelectionBehavior = .actionWithAutoDeselect
public var defaultHeaderHeight: CGFloat? = 0
public var defaultFooterHeight: CGFloat? = 0
public var defaultSpacingBetweenSections: CGFloat? = 20
public var defaultLastSectionFooter: CGFloat = 20
public lazy var defaultSeparatorInsetLeading: CGFloat = Self.cellHInnerMargin
public var defaultSeparatorInsetTrailing: CGFloat = 0
public var defaultCellHeight: CGFloat = 50
public var isUsingPresentedStyle: Bool {
return presentingViewController != nil
}
private static let cellIdentifier = "cellIdentifier"
public override init() {
super.init()
// We also do this in applyTheme(), but we also need to do it here
// for the case where we push multiple table views at the same time.
Self.removeBackButtonText(viewController: self)
tableView.tableViewDelegate = self
}
open override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.tableFooterView = UIView()
tableView.estimatedRowHeight = defaultCellHeight
view.addSubview(tableView)
// Pin top edge of tableView.
if let topHeader = topHeader {
view.addSubview(topHeader)
topHeader.autoPin(toTopLayoutGuideOf: self, withInset: 0)
topHeader.autoPinEdge(toSuperviewSafeArea: .leading)
topHeader.autoPinEdge(toSuperviewSafeArea: .trailing)
tableView.autoPinEdge(.top, to: .bottom, of: topHeader)
topHeader.setContentHuggingVerticalHigh()
topHeader.setCompressionResistanceVerticalHigh()
} else {
tableView.autoPinEdge(toSuperviewEdge: .top)
}
// Pin leading & trailing edges of tableView.
tableView.autoPinEdge(toSuperviewEdge: .leading)
tableView.autoPinEdge(toSuperviewEdge: .trailing)
tableView.setContentHuggingVerticalLow()
tableView.setCompressionResistanceVerticalLow()
// Pin bottom edge of tableView.
if let bottomFooter = bottomFooter {
view.addSubview(bottomFooter)
bottomFooter.autoPinEdge(.top, to: .bottom, of: tableView)
bottomFooter.autoPinEdge(toSuperviewSafeArea: .leading)
bottomFooter.autoPinEdge(toSuperviewSafeArea: .trailing)
bottomFooter.setContentHuggingVerticalHigh()
bottomFooter.setCompressionResistanceVerticalHigh()
}
updateBottomConstraint()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: Self.cellIdentifier)
applyContents()
applyTheme()
}
/// Applies theme and reloads table contents.
///
/// Does not reload header/footer views. Subclasses that use header/footer
/// views that need to update in response to theme changes should override
/// this method to do so manually.
open override func themeDidChange() {
super.themeDidChange()
applyTheme()
applyContents()
}
open var tableBackgroundColor: UIColor {
AssertIsOnMainThread()
return Self.tableBackgroundColor(
isUsingPresentedStyle: isUsingPresentedStyle,
forceDarkMode: forceDarkMode
)
}
private func applyTheme() {
applyTheme(to: self)
tableView.backgroundColor = self.tableBackgroundColor
tableView.sectionIndexColor = forceDarkMode ? Theme.darkThemePrimaryColor : Theme.primaryTextColor
updateNavbarStyling()
tableView.separatorColor = .clear
tableView.separatorInset = .zero
tableView.separatorStyle = .none
}
public var shouldHideBottomFooter = false {
didSet {
let didChange = oldValue != shouldHideBottomFooter
if didChange, isViewLoaded {
updateBottomConstraint()
}
}
}
private var bottomFooterConstraint: NSLayoutConstraint?
private func updateBottomConstraint() {
bottomFooterConstraint?.autoRemove()
bottomFooterConstraint = nil
// Pin bottom edge of tableView.
if !shouldHideBottomFooter,
let bottomFooter = bottomFooter {
if shouldAvoidKeyboard {
bottomFooterConstraint = bottomFooter.autoPinEdge(.bottom, to: .bottom, of: keyboardLayoutGuideViewSafeArea)
} else {
bottomFooterConstraint = bottomFooter.autoPinEdge(toSuperviewEdge: .bottom)
}
} else if shouldAvoidKeyboard {
bottomFooterConstraint = tableView.autoPinEdge(.bottom, to: .bottom, of: keyboardLayoutGuideViewSafeArea)
} else {
bottomFooterConstraint = tableView.autoPinEdge(toSuperviewEdge: .bottom)
}
bottomFooter?.isHidden = shouldHideBottomFooter
guard hasViewAppeared else {
return
}
struct ViewFrame {
let view: UIView
let frame: CGRect
func apply() {
view.frame = self.frame
}
}
func viewFrames(for views: [UIView]) -> [ViewFrame] {
views.map { ViewFrame(view: $0, frame: $0.frame) }
}
var animatedViews: [UIView] = [ tableView ]
if let bottomFooter = bottomFooter {
animatedViews.append(bottomFooter)
}
let viewFramesBefore = viewFrames(for: animatedViews)
self.view.layoutIfNeeded()
let viewFramesAfter = viewFrames(for: animatedViews)
for viewFrame in viewFramesBefore { viewFrame.apply() }
UIView.animate(withDuration: 0.15) {
for viewFrame in viewFramesAfter { viewFrame.apply() }
}
}
/// Reloads table contents when content size category changes.
///
/// Does not reload header/footer views. Subclasses that use header/footer
/// views that need to update in response to content size category changes
/// should override this method to do so manually.
open override func contentSizeCategoryDidChange() {
super.contentSizeCategoryDidChange()
// Reload when content size might need to change.
applyContents()
}
private var usesSolidNavbarStyle: Bool {
return tableView.contentOffset.y <= (defaultSpacingBetweenSections ?? 0) - tableView.adjustedContentInset.top
}
open var preferredNavigationBarStyle: OWSNavigationBarStyle {
return usesSolidNavbarStyle ? .solid : .blur
}
open var navbarBackgroundColorOverride: UIColor? {
return usesSolidNavbarStyle ? tableBackgroundColor : nil
}
private var hasViewAppeared = false
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
applyTheme()
tableView.tableFooterView = UIView()
hasViewAppeared = true
}
private func section(for index: Int) -> OWSTableSection? {
AssertIsOnMainThread()
guard let section = contents.sections[safe: index] else {
owsFailDebug("Missing section: \(index)")
return nil
}
return section
}
private func item(for indexPath: IndexPath) -> OWSTableItem? {
AssertIsOnMainThread()
guard let section = contents.sections[safe: indexPath.section] else {
owsFailDebug("Missing section: \(indexPath.section)")
return nil
}
guard let item = section.items[safe: indexPath.row] else {
owsFailDebug("Missing item: \(indexPath.row)")
return nil
}
return item
}
public var shouldDeferInitialLoad = true
private func applyContents(shouldReload: Bool = true) {
AssertIsOnMainThread()
if let title = contents.title, !title.isEmpty {
self.title = title
}
var shouldReload = shouldReload
if shouldDeferInitialLoad {
shouldReload = (shouldReload &&
self.isViewLoaded &&
tableView.width > 0)
}
if shouldReload {
tableView.reloadData()
}
}
public static func buildTopHeader(forView wrappedView: UIView,
vMargin: CGFloat = 0) -> UIView {
buildTopHeader(forView: wrappedView,
topMargin: vMargin,
bottomMargin: vMargin)
}
public static func buildTopHeader(forView wrappedView: UIView,
topMargin: CGFloat = 0,
bottomMargin: CGFloat = 0) -> UIView {
let wrapperStack = UIStackView()
wrapperStack.addArrangedSubview(wrappedView)
wrapperStack.axis = .vertical
wrapperStack.alignment = .fill
wrapperStack.isLayoutMarginsRelativeArrangement = true
let layoutMargins = cellOuterInsets(in: wrappedView)
wrapperStack.layoutMargins = layoutMargins
return wrapperStack
}
}
// MARK: -
extension OWSTableViewController2: UITableViewDataSource, UITableViewDelegate, OWSNavigationChildController {
public func tableView(_ tableView: UITableView, numberOfRowsInSection sectionIndex: Int) -> Int {
guard let section = self.section(for: sectionIndex) else {
owsFailDebug("Missing section: \(sectionIndex)")
return 0
}
return section.items.count
}
public func numberOfSections(in tableView: UITableView) -> Int {
contents.sections.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let item = self.item(for: indexPath) else {
owsFailDebug("Missing item: \(indexPath)")
let cell = OWSTableItem.newCell()
configureCellBackground(cell, indexPath: indexPath)
return cell
}
item.tableViewController = self
if let cell = item.getOrBuildCustomCell(tableView) {
configureCellBackground(cell, indexPath: indexPath)
return cell
}
guard let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: Self.cellIdentifier) else {
owsFailDebug("Missing cell: \(indexPath)")
let cell = OWSTableItem.newCell()
configureCellBackground(cell, indexPath: indexPath)
return cell
}
OWSTableItem.configureCell(cell)
if let title = item.title {
cell.textLabel?.text = title
}
configureCellBackground(cell, indexPath: indexPath)
return cell
}
public func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
guard let item = self.item(for: indexPath) else {
owsFailDebug("Missing item: \(indexPath)")
return
}
if let willDisplayBlock = item.willDisplayBlock {
willDisplayBlock(cell)
}
}
private func configureCellBackground(_ cell: UITableViewCell, indexPath: IndexPath) {
guard let section = contents.sections[safe: indexPath.section] else {
owsFailDebug("Missing section: \(indexPath.section)")
return
}
cell.backgroundView?.removeFromSuperview()
cell.backgroundView = nil
cell.selectedBackgroundView?.removeFromSuperview()
cell.backgroundColor = .clear
cell.contentView.backgroundColor = .clear
guard section.hasBackground else {
let selectedBackgroundView = UIView()
selectedBackgroundView.backgroundColor = forceDarkMode
? Theme.darkThemeTableCell2SelectedBackgroundColor
: Theme.tableCell2SelectedBackgroundColor
cell.selectedBackgroundView = selectedBackgroundView
return
}
let cellBackgroundColor: UIColor
let cellSelectedBackgroundColor: UIColor
if let customCell = cell as? CustomBackgroundColorCell {
cellBackgroundColor = customCell.customBackgroundColor(forceDarkMode: forceDarkMode)
cellSelectedBackgroundColor = customCell.customSelectedBackgroundColor(forceDarkMode: forceDarkMode)
} else {
cellBackgroundColor = self.cellBackgroundColor
cellSelectedBackgroundColor = self.cellSelectedBackgroundColor
}
cell.backgroundView = buildCellBackgroundView(
indexPath: indexPath,
section: section,
backgroundColor: cellBackgroundColor
)
cell.selectedBackgroundView = buildCellSelectedBackgroundView(
indexPath: indexPath,
section: section,
backgroundColor: cellSelectedBackgroundColor
)
// We use cellHOuterMargin _outside_ the background and cellHInnerMargin
// _inside_.
//
// By applying it to the cell, ensure the correct behavior for accessories.
cell.layoutMargins = cellOuterInsetsWithMargin(hMargin: Self.cellHInnerMargin, vMargin: 0)
var contentMargins = UIEdgeInsets(
hMargin: 0,
vMargin: Self.cellVInnerMargin
)
// Our table code is going to be vastly simpler if we DRY up the
// spacing between the cell content and the accessory here.
let hasAccessory = (cell.accessoryView != nil || cell.accessoryType != .none)
if hasAccessory {
if CurrentAppContext().isRTL {
contentMargins.left += 8
} else {
contentMargins.right += 8
}
}
cell.contentView.layoutMargins = contentMargins
}
/// Returns the frame representing the shape of a cell's visible pill, in
/// the given view.
public func cellPillFrame(view: UIView) -> CGRect {
var pillFrame = view.bounds.inset(by: self.cellOuterInsets)
pillFrame.x += view.safeAreaInsets.left
pillFrame.size.width -= view.safeAreaInsets.left + view.safeAreaInsets.right
return pillFrame
}
/// Configures the given layer to draw the background pill for a cell, in
/// the given view.
private func configureCellPillLayer(
pillLayer: CAShapeLayer,
view: UIView,
isFirstInSection: Bool,
isLastInSection: Bool,
backgroundColor: UIColor
) {
pillLayer.frame = view.bounds
pillLayer.fillColor = backgroundColor.cgColor
let pillFrame = cellPillFrame(view: view)
if
pillFrame.width > 0,
pillFrame.height > 0
{
var roundingCorners: UIRectCorner = []
if isFirstInSection {
roundingCorners.formUnion(.topLeft)
roundingCorners.formUnion(.topRight)
}
if isLastInSection {
roundingCorners.formUnion(.bottomLeft)
roundingCorners.formUnion(.bottomRight)
}
pillLayer.path = UIBezierPath(
roundedRect: pillFrame,
byRoundingCorners: roundingCorners,
cornerRadii: .square(OWSTableViewController2.cellRounding)
).cgPath
} else {
pillLayer.path = nil
}
}
private func configureCellSeparatorLayer(
separatorLayer: CAShapeLayer,
view: UIView,
sectionSeparatorInsetLeading: CGFloat?,
sectionSeparatorInsetTrailing: CGFloat?,
separatorColor: UIColor
) {
separatorLayer.frame = view.bounds
separatorLayer.fillColor = separatorColor.cgColor
var separatorFrame = cellPillFrame(view: view)
let separatorThickness: CGFloat = .hairlineWidth
separatorFrame.y = separatorFrame.height - separatorThickness
separatorFrame.size.height = separatorThickness
let separatorInsetLeading = sectionSeparatorInsetLeading ?? self.defaultSeparatorInsetLeading
let separatorInsetTrailing = sectionSeparatorInsetTrailing ?? self.defaultSeparatorInsetTrailing
separatorFrame.x += separatorInsetLeading
separatorFrame.size.width -= (separatorInsetLeading + separatorInsetTrailing)
separatorLayer.path = UIBezierPath(rect: separatorFrame).cgPath
}
private func buildCellBackgroundView(
indexPath: IndexPath,
section: OWSTableSection,
backgroundColor: UIColor
) -> UIView {
let isFirstInSection = indexPath.row == 0
let isLastInSection = indexPath.row == tableView(tableView, numberOfRowsInSection: indexPath.section) - 1
let pillLayer = CAShapeLayer()
var separatorLayer: CAShapeLayer?
let backgroundView = OWSLayerView(frame: .zero) { [weak self] view in
guard let self = self else { return }
self.configureCellPillLayer(
pillLayer: pillLayer,
view: view,
isFirstInSection: isFirstInSection,
isLastInSection: isLastInSection,
backgroundColor: backgroundColor
)
if let separatorLayer {
self.configureCellSeparatorLayer(
separatorLayer: separatorLayer,
view: view,
sectionSeparatorInsetLeading: section.separatorInsetLeading,
sectionSeparatorInsetTrailing: section.separatorInsetTrailing,
separatorColor: self.separatorColor
)
}
}
backgroundView.layer.addSublayer(pillLayer)
if
section.hasSeparators,
!isLastInSection
{
let separator = CAShapeLayer()
separatorLayer = separator
backgroundView.layer.addSublayer(separator)
}
return backgroundView
}
private func buildCellSelectedBackgroundView(
indexPath: IndexPath,
section: OWSTableSection,
backgroundColor: UIColor
) -> UIView {
let pillLayer = CAShapeLayer()
let isFirstInSection = indexPath.row == 0
let isLastInSection = indexPath.row == tableView(tableView, numberOfRowsInSection: indexPath.section) - 1
let backgroundView = OWSLayerView(frame: .zero) { [weak self] view in
guard let self = self else { return }
self.configureCellPillLayer(
pillLayer: pillLayer,
view: view,
isFirstInSection: isFirstInSection,
isLastInSection: isLastInSection,
backgroundColor: backgroundColor
)
}
backgroundView.layer.addSublayer(pillLayer)
return backgroundView
}
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
guard let item = self.item(for: indexPath) else {
owsFailDebug("Missing item: \(indexPath)")
return defaultCellHeight
}
if let customRowHeight = item.customRowHeight {
return customRowHeight
}
return UITableView.automaticDimension
}
public static let cellRounding: CGFloat = 10
public static var maximumInnerWidth: CGFloat { 496 }
public static var defaultHOuterMargin: CGFloat {
UIDevice.current.isPlusSizePhone ? 20 : 16
}
// The distance from the edge of the view to the cell border.
public static func cellOuterInsets(in view: UIView) -> UIEdgeInsets {
var insets = UIEdgeInsets()
if view.safeAreaInsets.left <= 0 {
insets.left = defaultHOuterMargin
}
if view.safeAreaInsets.right <= 0 {
insets.right = defaultHOuterMargin
}
let totalInnerWidth = view.width - insets.totalWidth
if totalInnerWidth > maximumInnerWidth {
let excessInnerWidth = totalInnerWidth - maximumInnerWidth
insets.left += excessInnerWidth / 2
insets.right += excessInnerWidth / 2
}
return insets
}
public var cellOuterInsets: UIEdgeInsets { Self.cellOuterInsets(in: view) }
public func cellOuterInsetsWithMargin(top: CGFloat = .zero, left: CGFloat = .zero, bottom: CGFloat = .zero, right: CGFloat = .zero) -> UIEdgeInsets {
UIEdgeInsets(
top: top,
left: left + cellHOuterLeftMargin,
bottom: bottom,
right: right + cellHOuterRightMargin
)
}
public func cellOuterInsetsWithMargin(hMargin: CGFloat, vMargin: CGFloat) -> UIEdgeInsets {
cellOuterInsetsWithMargin(top: vMargin, left: hMargin, bottom: vMargin, right: hMargin)
}
public static func cellHOuterLeftMargin(in view: UIView) -> CGFloat {
cellOuterInsets(in: view).left
}
public var cellHOuterLeftMargin: CGFloat { Self.cellHOuterLeftMargin(in: view) }
public static func cellHOuterRightMargin(in view: UIView) -> CGFloat {
cellOuterInsets(in: view).right
}
public var cellHOuterRightMargin: CGFloat { Self.cellHOuterRightMargin(in: view) }
// The distance from the cell border to the cell content.
public static var cellHInnerMargin: CGFloat {
UIDevice.current.isPlusSizePhone ? 20 : 16
}
// The distance from the cell border to the cell content.
public static var cellVInnerMargin: CGFloat {
13
}
private var automaticDimension: CGFloat {
UITableView.automaticDimension
}
private var headerFont: UIFont { .dynamicTypeBodyClamped.semibold() }
private var footerFont: UIFont { .dynamicTypeCaption1Clamped }
private func headerTextContainerInsets(for section: OWSTableSection) -> UIEdgeInsets {
headerTextContainerInsets(useDeepInsets: section.hasBackground)
}
private func headerTextContainerInsets(useDeepInsets: Bool) -> UIEdgeInsets {
var textContainerInset = cellOuterInsetsWithMargin(
top: (defaultSpacingBetweenSections ?? 0) + 12,
bottom: 10
)
if useDeepInsets {
textContainerInset.left += Self.cellHInnerMargin * 0.5
textContainerInset.right += Self.cellHInnerMargin * 0.5
}
textContainerInset.left += tableView.safeAreaInsets.left
textContainerInset.right += tableView.safeAreaInsets.right
return textContainerInset
}
private func footerTextContainerInsets(for section: OWSTableSection) -> UIEdgeInsets {
footerTextContainerInsets(useDeepInsets: section.hasBackground)
}
private func footerTextContainerInsets(useDeepInsets: Bool) -> UIEdgeInsets {
var textContainerInset = cellOuterInsetsWithMargin(top: 12)
if useDeepInsets {
textContainerInset.left += Self.cellHInnerMargin
textContainerInset.right += Self.cellHInnerMargin
}
textContainerInset.left += tableView.safeAreaInsets.left
textContainerInset.right += tableView.safeAreaInsets.right
return textContainerInset
}
private func buildDefaultHeaderOrFooter(height: CGFloat) -> UIView {
let view = UIView()
view.backgroundColor = .clear
view.autoSetDimension(.height, toSize: height)
return view
}
private func buildHeaderOrFooterTextView() -> UITextView {
let textView = LinkingTextView()
textView.backgroundColor = self.tableBackgroundColor
return textView
}
public func buildHeaderTextView(forSection section: OWSTableSection) -> UITextView {
let textView = buildHeaderTextView(withDeepInsets: section.hasBackground)
textView.delegate = section.headerTextViewDelegate
return textView
}
public func buildHeaderTextView(withDeepInsets: Bool) -> UITextView {
let textView = buildHeaderOrFooterTextView()
textView.textColor = (Theme.isDarkThemeEnabled || forceDarkMode) ? UIColor.ows_gray05 : UIColor.ows_gray90
textView.font = headerFont
textView.textContainerInset = headerTextContainerInsets(useDeepInsets: withDeepInsets)
return textView
}
public func buildFooterTextView(forSection section: OWSTableSection) -> UITextView {
let textView = buildFooterTextView(withDeepInsets: section.hasBackground)
textView.delegate = section.footerTextViewDelegate
return textView
}
public func buildFooterTextView(withDeepInsets: Bool) -> UITextView {
let textView = buildHeaderOrFooterTextView()
textView.textColor = forceDarkMode ? Theme.darkThemeSecondaryTextAndIconColor : Theme.secondaryTextAndIconColor
textView.font = footerFont
let linkTextAttributes: [NSAttributedString.Key: Any] = [
NSAttributedString.Key.foregroundColor: forceDarkMode ? Theme.darkThemePrimaryColor : Theme.primaryTextColor,
NSAttributedString.Key.font: footerFont,
NSAttributedString.Key.underlineStyle: 0
]
textView.linkTextAttributes = linkTextAttributes
textView.textContainerInset = footerTextContainerInsets(useDeepInsets: withDeepInsets)
return textView
}
public func tableView(_ tableView: UITableView, viewForHeaderInSection sectionIndex: Int) -> UIView? {
guard let section = contents.sections[safe: sectionIndex] else {
owsFailDebug("Missing section: \(sectionIndex)")
return nil
}
if let customHeaderView = section.customHeaderView {
return customHeaderView
} else if let headerTitle = section.headerTitle,
!headerTitle.isEmpty {
let textView = buildHeaderTextView(forSection: section)
textView.text = headerTitle
return textView
} else if let headerAttributedTitle = section.headerAttributedTitle,
!headerAttributedTitle.isEmpty {
let textView = buildHeaderTextView(forSection: section)
textView.attributedText = headerAttributedTitle
return textView
} else if let customHeaderHeight = section.customHeaderHeight,
customHeaderHeight > 0 {
return buildDefaultHeaderOrFooter(height: customHeaderHeight)
} else if let defaultHeaderHeight = defaultHeaderHeight,
defaultHeaderHeight > 0 {
return buildDefaultHeaderOrFooter(height: defaultHeaderHeight)
} else if let defaultSpacingBetweenSections = defaultSpacingBetweenSections,
defaultSpacingBetweenSections > 0, !section.items.isEmpty {
return buildDefaultHeaderOrFooter(height: defaultSpacingBetweenSections)
} else {
return nil
}
}
public func tableView(_ tableView: UITableView, viewForFooterInSection sectionIndex: Int) -> UIView? {
guard let section = contents.sections[safe: sectionIndex] else {
owsFailDebug("Missing section: \(sectionIndex)")
return nil
}
if let customFooterView = section.customFooterView {
return customFooterView
} else if let footerTitle = section.footerTitle,
!footerTitle.isEmpty {
let textView = buildFooterTextView(forSection: section)
textView.text = footerTitle
return textView
} else if let footerAttributedTitle = section.footerAttributedTitle,
!footerAttributedTitle.isEmpty {
let textView = buildFooterTextView(forSection: section)
textView.attributedText = footerAttributedTitle
return textView
} else if let customFooterHeight = section.customFooterHeight,
customFooterHeight > 0 {
return buildDefaultHeaderOrFooter(height: customFooterHeight)
} else if let defaultFooterHeight = defaultFooterHeight,
defaultFooterHeight > 0 {
return buildDefaultHeaderOrFooter(height: defaultFooterHeight)
} else if isLastSection(tableView, sectionIndex: sectionIndex),
defaultLastSectionFooter > 0 {
return buildDefaultHeaderOrFooter(height: defaultLastSectionFooter)
} else {
return nil
}
}
private func isLastSection(_ tableView: UITableView, sectionIndex: Int) -> Bool {
sectionIndex == numberOfSections(in: tableView) - 1
}
public func tableView(_ tableView: UITableView, heightForHeaderInSection sectionIndex: Int) -> CGFloat {
guard let section = contents.sections[safe: sectionIndex] else {
owsFailDebug("Missing section: \(sectionIndex)")
return 0
}
if let customHeaderHeight = section.customHeaderHeight {
owsAssertDebug(customHeaderHeight > 0 || customHeaderHeight == automaticDimension)
return customHeaderHeight
} else if let headerTitle = section.headerTitle, !headerTitle.isEmpty {
// Get around a bug sizing UITextView in iOS 16/17 by manually sizing instead
// of relying on UITableView.automaticDimension
if #available(iOS 18, *) { owsFailDebug("Canary to check if this has been fixed") }
let insets = headerTextContainerInsets(for: section)
// Reuse sizing code for CVText even though we aren't using a CVText here.
let height = CVText.measureLabel(
config: CVLabelConfig.unstyledText(
headerTitle,
font: headerFont,
textColor: .black, // doesn't matter for sizing
numberOfLines: 0,
lineBreakMode: .byWordWrapping,
textAlignment: .natural
),
maxWidth: tableView.frame.width - insets.totalWidth
).height
return height + insets.totalHeight
} else if let headerTitle = section.headerAttributedTitle, !headerTitle.isEmpty {
// Get around a bug sizing UITextView in iOS 16/17 by manually sizing instead
// of relying on UITableView.automaticDimension
if #available(iOS 18, *) { owsFailDebug("Canary to check if this has been fixed") }
let insets = headerTextContainerInsets(for: section)
// Reuse sizing code for CVText even though we aren't using a CVText here.
let height = CVText.measureLabel(
config: CVLabelConfig(
text: .attributedText(headerTitle),
displayConfig: .forMeasurement(font: headerFont),
font: headerFont,
textColor: .black, // doesn't matter for sizing
numberOfLines: 0,
lineBreakMode: .byWordWrapping,
textAlignment: .natural
),
maxWidth: tableView.frame.width - insets.totalWidth
).height
return height + insets.totalHeight
} else if nil != self.tableView(tableView, viewForHeaderInSection: sectionIndex) {
return automaticDimension
} else {
return 0
}
}
public func tableView(_ tableView: UITableView, heightForFooterInSection sectionIndex: Int) -> CGFloat {
guard let section = contents.sections[safe: sectionIndex] else {
owsFailDebug("Missing section: \(sectionIndex)")
return 0
}
if let customFooterHeight = section.customFooterHeight {
owsAssertDebug(customFooterHeight > 0 || customFooterHeight == automaticDimension)
return customFooterHeight
} else if let footerTitle = section.footerTitle, !footerTitle.isEmpty {
// Get around a bug sizing UITextView in iOS 16/17 by manually sizing instead
// of relying on UITableView.automaticDimension
if #available(iOS 18, *) { owsFailDebug("Canary to check if this has been fixed") }
let insets = footerTextContainerInsets(for: section)
// Reuse sizing code for CVText even though we aren't using a CVText here.
let height = CVText.measureLabel(
config: CVLabelConfig.unstyledText(
footerTitle,
font: footerFont,
textColor: .black, // doesn't matter for sizing
numberOfLines: 0,
lineBreakMode: .byWordWrapping,
textAlignment: .natural
),
maxWidth: tableView.frame.width - insets.totalWidth
).height
return height + insets.totalHeight
} else if let footerTitle = section.footerAttributedTitle, !footerTitle.isEmpty {
// Get around a bug sizing UITextView in iOS 16/17 by manually sizing instead
// of relying on UITableView.automaticDimension
if #available(iOS 18, *) { owsFailDebug("Canary to check if this has been fixed") }
let insets = footerTextContainerInsets(for: section)
// Reuse sizing code for CVText even though we aren't using a CVText here.
let height = CVText.measureLabel(
config: CVLabelConfig(
text: .attributedText(footerTitle),
displayConfig: .forMeasurement(font: footerFont),
font: footerFont,
textColor: .black, // doesn't matter for sizing
numberOfLines: 0,
lineBreakMode: .byWordWrapping,
textAlignment: .natural
),
maxWidth: tableView.frame.width - insets.totalWidth
).height
return height + insets.totalHeight
} else if nil != self.tableView(tableView, viewForFooterInSection: sectionIndex) {
return automaticDimension
} else {
return 0
}
}
// Called before the user changes the selection. Return a new indexPath, or nil, to change the proposed selection.
public func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
guard let item = self.item(for: indexPath) else {
owsFailDebug("Missing item: \(indexPath)")
return nil
}
if item.actionBlock != nil {
return indexPath
} else {
return nil
}
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch selectionBehavior {
case .actionWithAutoDeselect:
tableView.deselectRow(at: indexPath, animated: false)
case .toggleSelectionWithAction:
break
}
performAction(indexPath: indexPath)
}
public func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
switch selectionBehavior {
case .actionWithAutoDeselect:
return
case .toggleSelectionWithAction:
performAction(indexPath: indexPath)
}
}
private func performAction(indexPath: IndexPath) {
guard let item = self.item(for: indexPath) else {
owsFailDebug("Missing item: \(indexPath)")
return
}
if let actionBlock = item.actionBlock {
actionBlock()
}
}