-
Notifications
You must be signed in to change notification settings - Fork 172
/
Copy pathNavigationBar.swift
1036 lines (864 loc) · 41.8 KB
/
NavigationBar.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
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 (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
//
import UIKit
// MARK: - NavigationBarTopAccessoryViewAttributes
/// Layout attributes for a navigation bar's top accessory view.
@objc(MSFNavigationBarTopAccessoryViewAttributes)
open class NavigationBarTopAccessoryViewAttributes: NSObject {
/// The width multiplier is the propotion of the navigation bar's width that the top accessory view will occupy.
@objc public let widthMultiplier: CGFloat
/// The maximum width of the top accessory view.
@objc public let maxWidth: CGFloat
/// The minimum width of the top accessory view.
@objc public let minWidth: CGFloat
@objc public init(widthMultiplier: CGFloat, maxWidth: CGFloat, minWidth: CGFloat) {
self.widthMultiplier = widthMultiplier
self.maxWidth = maxWidth
self.minWidth = minWidth
super.init()
}
public override init() {
self.widthMultiplier = 1.0
self.maxWidth = .greatestFiniteMagnitude
self.minWidth = .zero
}
}
/// Layout attributes for a navigation bar's top search bar.
@objc(MSFNavigationBarTopSearchBarAttributes)
open class NavigationBarTopSearchBarAttributes: NavigationBarTopAccessoryViewAttributes {
@objc public override init() {
super.init(widthMultiplier: Constants.widthMultiplier, maxWidth: Constants.viewMaxWidth, minWidth: Constants.viewMinWidth)
}
private struct Constants {
static let widthMultiplier: CGFloat = 0.375
static let viewMinWidth: CGFloat = 264
static let viewMaxWidth: CGFloat = 552
}
}
// MARK: - NavigationBarTitleAccessory
@objc(MSFNavigationBarTitleAccessoryDelegate)
/// Handles user interactions with a `NavigationBar` with an accessory.
public protocol NavigationBarTitleAccessoryDelegate {
@objc func navigationBarDidTapOnTitle(_ sender: NavigationBar)
}
/// The specifications for an accessory to show in the title or subtitle of the navigation bar.
@objc(MSFNavigationBarTitleAccessory)
open class NavigationBarTitleAccessory: NSObject {
/// Specifies a location where the title accessory should appear within the navigation bar.
@objc(MSFNavigationBarTitleAccessoryLocation)
public enum Location: Int {
case title
case subtitle
}
/// The style of title accessory to show.
@objc(MSFNavigationBarTitleAccessoryStyle)
public enum Style: Int {
case disclosure
case downArrow
case custom
}
/// The location of the accessory.
public let location: Location
/// The style of the accessory.
public let style: Style
/// A delegate that handles title press actions.
public weak var delegate: NavigationBarTitleAccessoryDelegate?
public init(location: Location, style: Style, delegate: NavigationBarTitleAccessoryDelegate? = nil) {
self.location = location
self.style = style
self.delegate = delegate
}
}
// MARK: - NavigationBarBackButtonDelegate
/// Handles presses from the back button shown with a leading-aligned title.
@objc(MSFNavigationBarBackButtonDelegate)
protocol NavigationBarBackButtonDelegate {
func backButtonWasPressed()
}
// MARK: - NavigationBar
/// UINavigationBar subclass, with a content view that contains various custom UIElements
/// Contains the MSNavigationTitleView class and handles passing animatable progress through
/// Custom UI can be hidden if desired
@objc(MSFNavigationBar)
open class NavigationBar: UINavigationBar, TokenizedControl, TwoLineTitleViewDelegate {
/// If the style is `.custom`, UINavigationItem's `navigationBarColor` is used for all the subviews' backgroundColor
@objc(MSFNavigationBarStyle)
public enum Style: Int {
case `default`
case primary
case system
case custom
case gradient
}
@objc(MSFNavigationBarTitleStyle)
/// Describes the style in which the title is shown in a navigation bar.
public enum TitleStyle: Int {
/// Shows a center-aligned title and/or subtitle. Most closely aligned with UIKit's default. Not capable of showing an avatar.
case system
/// Shows a leading-aligned title and/or subtitle. Also capable of showing an avatar.
case leading
/// Shows a large title. This option always ignores the subtitle. Also capable of showing an avatar.
case largeLeading
public var usesLeadingAlignment: Bool {
self != .system
}
}
@objc public class BadgeLabelStyleWrapper: NSObject {
public var style: BadgeLabelStyle
@objc public init(style: BadgeLabelStyle) {
self.style = style
}
}
@objc public static func navigationBarBackgroundColor(fluentTheme: FluentTheme?) -> UIColor {
return backgroundColor(for: .system, theme: fluentTheme)
}
/// Describes the sizing behavior of navigation bar elements (title, avatar, bar height)
@objc(MSFNavigationBarElementSize)
public enum ElementSize: Int {
case automatic, contracted, expanded
}
@objc(MSFNavigationBarShadow)
public enum Shadow: Int {
case automatic
case alwaysHidden
}
public typealias TokenSetKeyType = NavigationBarTokenSet.Tokens
public lazy var tokenSet: NavigationBarTokenSet = .init(style: { [weak self] in
self?.style ?? NavigationBar.defaultStyle
})
static let expansionContractionAnimationDuration: TimeInterval = 0.1 // the interval over which the expansion/contraction animations occur
private static let defaultStyle: Style = .primary
/// An object that conforms to the `MSFPersona` protocol and provides text and an optional image for display as an `MSAvatar` next to the large title. Only displayed if `showsLargeTitle` is true on the current navigation item. If avatar is nil, it won't show the avatar view.
@objc open var personaData: Persona? {
didSet {
titleView.personaData = personaData
}
}
/// A string to optionally customize the accessibility label of the large title's avatar
@objc open var avatarCustomAccessibilityLabel: String? {
didSet {
titleView.avatarCustomAccessibilityLabel = avatarCustomAccessibilityLabel
}
}
/// The accessibility label that should be applied for the back button.
/// A temporary change so that consumers who use SwiftUI for navigation can avoid duplicated resources until support of a swiftUI control is available.
@objc public static let backButtonAccessibilityLabel: String = "Accessibility.NavigationBar.BackLabel".localized
/// An element size to describe the behavior of large title's avatar. If `.automatic`, avatar will resize when `expand(animated:)` and `contract(animated:)` are called.
@objc open var avatarSize: ElementSize = .automatic {
didSet {
updateElementSizes()
}
}
@objc public func visibleAvatarView() -> UIView? {
if contentStackView.alpha != 0 {
return titleView.visibleAvatarView()
}
return nil
}
/// Returns the first match of an optional view for a bar button item with the given tag.
@objc public func barButtonItemView(with tag: Int) -> UIView? {
if usesLeadingTitle {
let totalBarButtonItemViews = leftBarButtonItemsStackView.arrangedSubviews + rightBarButtonItemsStackView.arrangedSubviews
for view in totalBarButtonItemViews {
if view.tag == tag {
return view
}
}
} else {
let totalBarButtonItems = (topItem?.leftBarButtonItems ?? []) + (topItem?.rightBarButtonItems ?? [])
for item in totalBarButtonItems {
if item.tag == tag {
return item.value(forKey: "view") as? UIView
}
}
}
return nil
}
/// An element size to describe the behavior of the navigation bar's expanded height. Set automatically when the values of `avatarSize` and `titleSize` are changed. The bar will lock to expanded size if either element is set to `.expanded`, lock to contracted if both elements are `.contracted`, and stay automatic in any other case.
@objc open private(set) dynamic var barHeight: ElementSize = .automatic {
didSet {
guard barHeight != oldValue else {
return
}
let originalIsExpanded = isExpanded
switch barHeight {
case .automatic:
if isExpanded {
expand(true)
} else {
contract(true)
}
case .contracted:
contract(true)
case .expanded:
expand(true)
}
isExpanded = originalIsExpanded
}
}
/// The main gradient layer to be applied to the NavigationBar's standardAppearance with the gradient style.
@objc public var gradient: CAGradientLayer? {
didSet {
updateGradient()
}
}
/// The layer used to mask the main gradient of the NavigationBar. If unset, only the main gradient will be displayed on the NavigationBar.
@objc public var gradientMask: CAGradientLayer? {
didSet {
updateGradient()
}
}
/// An element size to describe the behavior of the navigation bar's large title. If `.automatic`, the title label will resize when `expand(animated:)` and `contract(animated:)` are called.
@objc open var titleSize: ElementSize = .automatic {
didSet {
updateElementSizes()
}
}
/// An optional closure to be called when the avatar view is tapped, if it is present.
@objc open var onAvatarTapped: (() -> Void)? {
didSet {
titleView.onAvatarTapped = onAvatarTapped
}
}
/// The navigation bar's default leading content margin.
@objc public static let defaultContentLeadingMargin: CGFloat = 8
/// The navigation bar's default trailing content margin.
@objc public static let defaultContentTrailingMargin: CGFloat = 6
/// The navigation bar's leading content margin.
@objc open var contentLeadingMargin: CGFloat = defaultContentLeadingMargin {
didSet {
if oldValue != contentLeadingMargin {
updateContentStackViewMargins(forExpandedContent: contentIsExpanded)
}
}
}
/// The navigation bar's trailing content margin.
@objc open var contentTrailingMargin: CGFloat = defaultContentTrailingMargin {
didSet {
if oldValue != contentTrailingMargin {
updateContentStackViewMargins(forExpandedContent: contentIsExpanded)
}
}
}
open override var center: CGPoint {
get { return super.center }
set {
var newValue = newValue
// Workaround for iOS bug: when nav bar is hidden and device is rotated, the hidden nav bar get pushed up by additional 20px (status bar height) and when nav bar gets shown it animates from too far position leaving a 20px gap that shows window background (black by default) - this will then also affect nav bar hiding animation.
newValue.y = max(-frame.height / 2, newValue.y)
super.center = newValue
}
}
var titleView = AvatarTitleView() {
willSet {
titleView.removeFromSuperview()
}
didSet {
contentStackView.insertArrangedSubview(titleView, at: 0)
titleView.setContentHuggingPriority(.required, for: .horizontal)
titleView.setContentCompressionResistancePriority(.required, for: .horizontal)
}
}
// @objc dynamic - so we can do KVO on this
@objc dynamic private(set) var style: Style = defaultStyle
// Override value for BadgeLabel Style. We can set to nil when we don't wanna override.
@objc public var overriddenBadgeLabelStyle: BadgeLabelStyleWrapper? {
didSet {
if let navigationItem = topItem {
updateBarButtonItems(with: navigationItem)
}
}
}
private var systemWantsCompactNavigationBar: Bool {
return traitCollection.horizontalSizeClass == .compact && traitCollection.verticalSizeClass == .compact
}
let backgroundView = UIView() // used for coloration
// used to cover the navigationbar during animated transitions between VCs
private let contentStackView = ContentStackView() // used to contain the various custom UI Elements
private let rightBarButtonItemsStackView = UIStackView()
private let leftBarButtonItemsStackView = UIStackView()
private let preTitleSpacerView = UIView() // defines the spacing before the title, used for compact centered titles
private let postTitleSpacerView = UIView() // defines the spacing after the title, also the leading space between the left and right barbuttonitems stack
private let trailingSpacerView = UIView() // defines the trailing space between the left and right barbuttonitems stack
private var topAccessoryView: UIView?
private var topAccessoryViewConstraints: [NSLayoutConstraint] = []
private var titleViewConstraint: NSLayoutConstraint?
private(set) var usesLeadingTitle: Bool = true {
didSet {
if usesLeadingTitle == oldValue {
return
}
updateAccessibilityElements()
updateViewsForNavigationItem(topItem)
}
}
private var leftBarButtonItemsObserver: NSKeyValueObservation?
private var rightBarButtonItemsObserver: NSKeyValueObservation?
private var titleObserver: NSKeyValueObservation?
private var subtitleObserver: NSKeyValueObservation?
private var titleAccessoryObserver: NSKeyValueObservation?
private var titleImageObserver: NSKeyValueObservation?
private var navigationBarColorObserver: NSKeyValueObservation?
private var accessoryViewObserver: NSKeyValueObservation?
private var topAccessoryViewObserver: NSKeyValueObservation?
private var topAccessoryViewAttributesObserver: NSKeyValueObservation?
private var navigationBarStyleObserver: NSKeyValueObservation?
private var navigationBarShadowObserver: NSKeyValueObservation?
private var titleStyleObserver: NSKeyValueObservation?
private let backButtonItem: UIBarButtonItem = {
let backButtonItem = UIBarButtonItem(image: UIImage.staticImageNamed("back-24x24"),
style: .plain,
target: nil,
action: #selector(NavigationBarBackButtonDelegate.backButtonWasPressed))
backButtonItem.accessibilityIdentifier = "Back"
backButtonItem.accessibilityLabel = backButtonAccessibilityLabel
return backButtonItem
}()
weak var backButtonDelegate: NavigationBarBackButtonDelegate? {
didSet {
backButtonItem.target = backButtonDelegate
}
}
@objc public override init(frame: CGRect) {
super.init(frame: frame)
initBase()
}
@objc public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initBase()
}
/// Custom base initializer, used regardless of entry point
/// Sets up the custom interface
private func initBase() {
clipsToBounds = true
contain(view: backgroundView)
setupContentStackView()
contentStackView.isLayoutMarginsRelativeArrangement = true
updateContentStackViewMargins(forExpandedContent: true)
contentStackView.addInteraction(UILargeContentViewerInteraction())
// leftBarButtonItemsStackView: layout priorities are slightly lower to make sure titleView has the highest priority in horizontal spacing
contentStackView.addArrangedSubview(leftBarButtonItemsStackView)
leftBarButtonItemsStackView.setContentHuggingPriority(.defaultHigh, for: .horizontal)
leftBarButtonItemsStackView.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)
// preTitleSpacerView
contentStackView.addArrangedSubview(preTitleSpacerView)
preTitleSpacerView.backgroundColor = .clear
preTitleSpacerView.setContentHuggingPriority(.defaultHigh, for: .horizontal)
preTitleSpacerView.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
// titleView
contentStackView.addArrangedSubview(titleView)
titleView.setContentHuggingPriority(.required, for: .horizontal)
titleView.setContentCompressionResistancePriority(.required, for: .horizontal)
// postTitleSpacerView
contentStackView.addArrangedSubview(postTitleSpacerView)
postTitleSpacerView.backgroundColor = .clear
postTitleSpacerView.setContentHuggingPriority(.defaultLow, for: .horizontal)
postTitleSpacerView.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
// trailingSpacerView
contentStackView.addArrangedSubview(trailingSpacerView)
trailingSpacerView.backgroundColor = .clear
trailingSpacerView.setContentHuggingPriority(.defaultLow, for: .horizontal)
trailingSpacerView.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
// rightBarButtonItemsStackView: layout priorities are slightly lower to make sure titleView has the highest priority in horizontal spacing
contentStackView.addArrangedSubview(rightBarButtonItemsStackView)
rightBarButtonItemsStackView.setContentHuggingPriority(.defaultHigh, for: .horizontal)
rightBarButtonItemsStackView.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)
isTranslucent = false
// Cache the system shadow color
systemShadowColor = standardAppearance.shadowColor
updateColors(for: topItem)
updateViewsForNavigationItem(topItem)
updateAccessibilityElements()
tokenSet.registerOnUpdate(for: self) { [weak self] in
self?.updateColors(for: self?.topItem)
self?.updateTitleViewTokenSets()
}
}
private func updateGradient() {
guard style == .gradient, let gradient = gradient else {
return
}
gradient.frame = bounds
if let gradientMask = gradientMask {
gradientMask.frame = gradient.bounds
gradient.mask = gradientMask
}
let renderer = UIGraphicsImageRenderer(bounds: gradient.bounds)
let gradientImage = renderer.image { rendererContext in
gradient.render(in: rendererContext.cgContext)
}
standardAppearance.backgroundImage = gradientImage
}
private func updateTopAccessoryView(for navigationItem: UINavigationItem?) {
if let topAccessoryView = topAccessoryView {
topAccessoryView.removeFromSuperview()
}
self.topAccessoryView = navigationItem?.topAccessoryView
if let topAccessoryView = self.topAccessoryView {
topAccessoryView.translatesAutoresizingMaskIntoConstraints = false
let insertionIndex = contentStackView.arrangedSubviews.firstIndex(of: postTitleSpacerView)! + 1
contentStackView.insertArrangedSubview(topAccessoryView, at: insertionIndex)
NSLayoutConstraint.deactivate(topAccessoryViewConstraints)
topAccessoryViewConstraints.removeAll()
topAccessoryViewConstraints.append(contentsOf: [
topAccessoryView.centerXAnchor.constraint(equalTo: centerXAnchor),
topAccessoryView.centerYAnchor.constraint(equalTo: centerYAnchor)
])
if let attributes = navigationItem?.topAccessoryViewAttributes {
let widthConstraint = topAccessoryView.widthAnchor.constraint(equalTo: widthAnchor, multiplier: attributes.widthMultiplier)
widthConstraint.priority = .defaultHigh
let maxWidthConstraint = topAccessoryView.widthAnchor.constraint(lessThanOrEqualToConstant: attributes.maxWidth)
maxWidthConstraint.priority = .defaultHigh
topAccessoryViewConstraints.append(contentsOf: [
widthConstraint,
maxWidthConstraint,
topAccessoryView.widthAnchor.constraint(greaterThanOrEqualToConstant: attributes.minWidth)
])
}
NSLayoutConstraint.activate(topAccessoryViewConstraints)
}
}
// Manually contains the content stack view with lower priority constraints in order to avoid invalid simultaneous constraints when nav bar is hidden.
private func setupContentStackView() {
contentStackView.translatesAutoresizingMaskIntoConstraints = false
addSubview(contentStackView)
let identifierHeader = String(describing: type(of: contentStackView))
let leading = contentStackView.leadingAnchor.constraint(equalTo: leadingAnchor)
leading.identifier = identifierHeader + "_containmentLeading"
let trailing = contentStackView.trailingAnchor.constraint(equalTo: trailingAnchor)
trailing.identifier = identifierHeader + "_containmentTrailing"
trailing.priority = .defaultHigh
let top = contentStackView.topAnchor.constraint(equalTo: topAnchor)
top.identifier = identifierHeader + "_containmentTop"
let bottom = contentStackView.bottomAnchor.constraint(equalTo: bottomAnchor)
bottom.identifier = identifierHeader + "_containmentBottom"
bottom.priority = .defaultHigh
NSLayoutConstraint.activate([leading, trailing, top, bottom])
// These are consistent with UIKit's default navigation bar
contentStackView.minimumContentSizeCategory = .large
contentStackView.maximumContentSizeCategory = .extraExtraLarge
}
private func updateContentStackViewMargins(forExpandedContent contentIsExpanded: Bool) {
let contentHeight = contentIsExpanded ? TokenSetType.expandedContentHeight : TokenSetType.normalContentHeight
contentStackView.directionalLayoutMargins = NSDirectionalEdgeInsets(
top: 0,
leading: contentLeadingMargin,
bottom: contentHeight - TokenSetType.systemHeight,
trailing: contentTrailingMargin
)
}
open override func willMove(toWindow newWindow: UIWindow?) {
super.willMove(toWindow: newWindow)
guard let newWindow else {
return
}
tokenSet.update(newWindow.fluentTheme)
updateTitleViewTokenSets()
if let navigationItem = topItem {
let (_, actualItem) = actualStyleAndItem(for: navigationItem)
updateColors(for: actualItem)
} else {
updateColors(for: topItem)
}
}
private func updateTitleViewTokenSets() {
titleView.tokenSet.setOverrides(from: tokenSet, mapping: [
.titleColor: .titleColor,
.titleFont: .titleFont,
.subtitleColor: .subtitleColor,
.subtitleFont: .subtitleFont,
.largeTitleFont: .largeTitleFont
])
}
/// Guarantees that the custom UI remains on top of the subview stack
/// Fetches the current navigation item and triggers a UI update
open override func layoutSubviews() {
super.layoutSubviews()
bringSubviewToFront(backgroundView)
bringSubviewToFront(contentStackView)
updateAccessibilityElements()
}
open override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
// contentStackView's content extends its bounds outside of navigation bar bounds
return super.point(inside: point, with: event) ||
contentStackView.point(inside: convert(point, to: contentStackView), with: event)
}
@available(iOS, deprecated: 17.0)
open override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if traitCollection.verticalSizeClass != previousTraitCollection?.verticalSizeClass {
updateElementSizes()
updateContentStackViewMargins(forExpandedContent: contentIsExpanded)
updateViewsForNavigationItem(topItem)
updateTitleViewConstraints()
// change bar button image size and title inset depending on device rotation
if let navigationItem = topItem {
updateSubtitleView(for: navigationItem)
if usesLeadingTitle {
updateBarButtonItems(with: navigationItem)
}
}
}
}
/// Override the avatar with given style rather than using avatar data
/// - Parameter style: style used in the avatar
@objc open func overrideAvatar(with style: MSFAvatarStyle) {
titleView.avatarOverrideStyle = style
}
// MARK: Element size handling
private var currentAvatarSize: ElementSize {
if traitCollection.verticalSizeClass == .compact {
return .contracted
}
return avatarSize
}
private var currentTitleSize: ElementSize {
if traitCollection.verticalSizeClass == .compact {
return .contracted
}
return titleSize
}
private var currentBarHeight: ElementSize {
if currentAvatarSize == .expanded || currentTitleSize == .expanded {
return .expanded
} else if currentAvatarSize == .contracted && currentTitleSize == .contracted {
return .contracted
} else {
return .automatic
}
}
private var contentIsExpanded: Bool {
return barHeight == .automatic ? isExpanded : barHeight == .expanded
}
private func updateElementSizes() {
titleView.avatarSize = currentAvatarSize
barHeight = currentBarHeight
}
// MARK: UINavigationItem & UIBarButtonItem handling
func updateColors(for navigationItem: UINavigationItem?) {
let backgroundColor = navigationItem?.navigationBarColor(fluentTheme: tokenSet.fluentTheme)
let shouldHideSystemTitle: Bool = (style == .gradient || (backgroundColor?.resolvedColor(with: traitCollection).cgColor.alpha ?? 1.0) < 1.0) && usesLeadingTitle
let systemTitleColor = shouldHideSystemTitle ? UIColor.clear : tokenSet[.titleColor].uiColor
switch style {
case .primary, .default, .custom:
titleView.style = .primary
case .system, .gradient:
titleView.style = .system
}
backgroundView.backgroundColor = style == .gradient ? .clear : backgroundColor
standardAppearance.backgroundColor = backgroundColor
tintColor = tokenSet[.buttonTintColor].uiColor
standardAppearance.titleTextAttributes[NSAttributedString.Key.foregroundColor] = systemTitleColor
standardAppearance.largeTitleTextAttributes[NSAttributedString.Key.foregroundColor] = systemTitleColor
// Update the scroll edge appearance to match the new standard appearance
scrollEdgeAppearance = standardAppearance
navigationBarColorObserver = navigationItem?.observe(\.customNavigationBarColor) { [unowned self] navigationItem, _ in
// Unlike title or barButtonItems that depends on the topItem, navigation bar color can be set from the parentViewController's navigationItem
self.updateColors(for: navigationItem)
}
}
func update(with navigationItem: UINavigationItem) {
let (actualStyle, actualItem) = actualStyleAndItem(for: navigationItem)
style = actualStyle
updateColors(for: actualItem)
updateGradient()
usesLeadingTitle = navigationItem.titleStyle.usesLeadingAlignment
updateShadow(for: navigationItem)
updateTopAccessoryView(for: navigationItem)
updateSubtitleView(for: navigationItem)
titleView.update(with: navigationItem)
updateTitleViewConstraints()
if navigationItem.backButtonTitle == nil {
navigationItem.backButtonTitle = ""
}
updateBarButtonItems(with: navigationItem)
// Force layout to avoid animation
layoutIfNeeded()
leftBarButtonItemsObserver = navigationItem.observe(\UINavigationItem.leftBarButtonItems) { [unowned self] item, _ in
self.navigationItemDidUpdate(item)
}
rightBarButtonItemsObserver = navigationItem.observe(\UINavigationItem.rightBarButtonItems) { [unowned self] item, _ in
self.navigationItemDidUpdate(item)
}
titleObserver = navigationItem.observe(\UINavigationItem.title) { [unowned self] item, _ in
self.navigationItemDidUpdate(item)
}
subtitleObserver = navigationItem.observe(\UINavigationItem.subtitle) { [unowned self] item, _ in
self.navigationItemDidUpdate(item)
}
titleAccessoryObserver = navigationItem.observe(\UINavigationItem.titleAccessory) { [unowned self] item, _ in
self.navigationItemDidUpdate(item)
}
titleImageObserver = navigationItem.observe(\UINavigationItem.titleImage) { [unowned self] item, _ in
self.navigationItemDidUpdate(item)
}
accessoryViewObserver = navigationItem.observe(\UINavigationItem.accessoryView) { [unowned self] item, _ in
self.navigationItemDidUpdate(item)
}
topAccessoryViewObserver = navigationItem.observe(\UINavigationItem.topAccessoryView) { [unowned self] item, _ in
self.navigationItemDidUpdate(item)
}
topAccessoryViewAttributesObserver = navigationItem.observe(\UINavigationItem.topAccessoryViewAttributes) { [unowned self] item, _ in
self.navigationItemDidUpdate(item)
}
navigationBarStyleObserver = navigationItem.observe(\UINavigationItem.navigationBarStyle) { [unowned self] item, _ in
self.navigationItemDidUpdate(item)
}
navigationBarShadowObserver = navigationItem.observe(\UINavigationItem.navigationBarShadow) { [unowned self] item, _ in
self.navigationItemDidUpdate(item)
}
titleStyleObserver = navigationItem.observe(\UINavigationItem.titleStyle) { [unowned self] item, _ in
self.navigationItemDidUpdate(item)
}
}
func actualStyleAndItem(for navigationItem: UINavigationItem) -> (style: Style, item: UINavigationItem) {
if navigationItem.navigationBarStyle != .default {
return (navigationItem.navigationBarStyle, navigationItem)
}
if let items = items?.prefix(while: { $0 != navigationItem }),
let item = items.last(where: { $0.navigationBarStyle != .default }) {
return (item.navigationBarStyle, item)
}
return (NavigationBar.defaultStyle, navigationItem)
}
private func createBarButtonItemButton(with item: UIBarButtonItem, isLeftItem: Bool) -> UIButton {
let button = BadgeLabelButton(type: .system)
button.item = item
if let badgeLabelStyle = overriddenBadgeLabelStyle?.style {
button.badgeLabelStyle = badgeLabelStyle
} else if style == .system {
button.badgeLabelStyle = .system
} else if style == .gradient {
button.badgeLabelStyle = .brand
} else {
button.badgeLabelStyle = .onPrimary
}
// We want to hide the native right bar button items for non-system title styles when using the gradient style.
if style == .gradient && !isLeftItem && usesLeadingTitle {
item.tintColor = .clear
// Since changing the native item's tintColor gets passed down to the button, we need to re-set its tintColor.
button.tintColor = tokenSet[.buttonTintColor].uiColor
}
let horizontalInset = isLeftItem ? TokenSetType.leftBarButtonItemHorizontalInset : TokenSetType.rightBarButtonItemHorizontalInset
let insets = NSDirectionalEdgeInsets(top: 0,
leading: horizontalInset,
bottom: 0,
trailing: horizontalInset)
button.configuration?.contentInsets = insets
return button
}
/// Updates the bar button items.
///
/// In general, this should be called as late as possible when receiving a new navigation item
/// because it will replace a client-provided left bar button item with a back button if needed.
private func updateBarButtonItems(with navigationItem: UINavigationItem) {
// only one left bar button item is support for large title view
if navigationItem != items?.first {
// Back button takes priority over client-provided leftBarButtonItem
// navigationItem != items?.first is sufficient for knowing we won't be at the
// root element of our navigation controller. This is because UINavigationItems
// are unique to their view controllers, and you can't push the same view controller
// onto a navigation stack more than once.
leftBarButtonItemsStackView.isHidden = false
// This gets called before the navigation stack gets updated
if let items = items, let navigationItemIndex = items.firstIndex(of: navigationItem), navigationItemIndex > 0 {
let upcomingBackItem = items[navigationItemIndex - 1]
backButtonItem.title = upcomingBackItem.backButtonTitle
} else {
// Assume that this item is getting pushed onto the stack
backButtonItem.title = topItem?.backButtonTitle
}
if navigationItem.titleStyle == .system {
let button = createBarButtonItemButton(with: backButtonItem, isLeftItem: true)
// The OS already gives us the leading margin we want, so no need for additional insets
button.configuration?.contentInsets.leading = 0
navigationItem.leftBarButtonItem = UIBarButtonItem(customView: button)
}
refresh(barButtonStack: leftBarButtonItemsStackView, with: [backButtonItem], isLeftItem: true)
// Hide the system's back button to avoid having duplicated back buttons with the gradient style.
if style == .gradient {
navigationItem.hidesBackButton = true
}
} else if let leftBarButtonItem = navigationItem.leftBarButtonItem {
leftBarButtonItemsStackView.isHidden = false
refresh(barButtonStack: leftBarButtonItemsStackView, with: [leftBarButtonItem], isLeftItem: true)
} else {
leftBarButtonItemsStackView.isHidden = true
}
refresh(barButtonStack: rightBarButtonItemsStackView, with: navigationItem.rightBarButtonItems?.reversed(), isLeftItem: false)
}
private func refresh(barButtonStack: UIStackView, with items: [UIBarButtonItem]?, isLeftItem: Bool) {
barButtonStack.removeAllSubviews()
items?.forEach { item in
barButtonStack.addArrangedSubview(createBarButtonItemButton(with: item, isLeftItem: isLeftItem))
}
}
private func navigationItemDidUpdate(_ navigationItem: UINavigationItem) {
if navigationItem == topItem {
update(with: navigationItem)
}
}
// MARK: Obscurant handling
func obscureContent(animated: Bool) {
if contentStackView.alpha == 1 {
if animated {
UIView.animate(withDuration: TokenSetType.obscuringAnimationDuration) {
self.contentStackView.alpha = 0
}
} else {
contentStackView.alpha = 0
}
}
}
func revealContent(animated: Bool) {
if contentStackView.alpha == 0 {
if animated {
UIView.animate(withDuration: TokenSetType.revealingAnimationDuration) {
self.contentStackView.alpha = 1
}
} else {
contentStackView.alpha = 1
}
}
}
// MARK: Large/Normal Title handling
/// Cache for the system shadow color, since the default value is private.
private var systemShadowColor: UIColor?
private func updateViewsForNavigationItem(_ navigationItem: UINavigationItem?) {
// UIView.isHidden has a bug where a series of repeated calls with the same parameter can "glitch" the view into a permanent shown/hidden state
// i.e. repeatedly trying to hide a UIView that is already in the hidden state
// by adding a check to the isHidden property prior to setting, we avoid such problematic scenarios
// The compact (32px) bar doesn't hold a TwoLineTitleView very well, and due to
// UINavigationBar's internal view hierarchy, we can't propagate touch events on
// parts that are outside that 32px range to the actual title view.
// We therefore depend on the "fake" navigation bar that we use for leading titles to save the day.
// We also want to hide the backgroundView and the contentStackView for gradient style regular title to
// avoid displaying duplicated navigation bar items.
let shouldHideSystemNavigationItems = usesLeadingTitle || (style != .gradient && systemWantsCompactNavigationBar && navigationItem?.titleView == nil)
if shouldHideSystemNavigationItems {
if backgroundView.isHidden {
backgroundView.isHidden = false
}
if contentStackView.isHidden {
contentStackView.isHidden = false
}
} else {
if !backgroundView.isHidden {
backgroundView.isHidden = true
}
if !contentStackView.isHidden {
contentStackView.isHidden = true
}
}
updateShadow(for: navigationItem)
}
private func updateTitleViewConstraints() {
titleViewConstraint?.isActive = false
let bottomConstraint = titleView.bottomAnchor.constraint(equalTo: bottomAnchor)
// We lower the priority of this constraint to avoid breaking auto-layout's generated constraints
// when the navigation bar is hidden.
bottomConstraint.priority = .defaultHigh
preTitleSpacerView.isHidden = usesLeadingTitle
bottomConstraint.isActive = true
titleViewConstraint = bottomConstraint
}
private func updateShadow(for navigationItem: UINavigationItem?) {
if needsShadow(for: navigationItem) {
standardAppearance.shadowColor = systemShadowColor
} else {
standardAppearance.shadowColor = nil
}
// Update the scroll edge shadow to match standard
scrollEdgeAppearance = standardAppearance
}
private func needsShadow(for navigationItem: UINavigationItem?) -> Bool {
switch navigationItem?.navigationBarShadow ?? .automatic {
case .automatic:
return !usesLeadingTitle && style == .system && !systemWantsCompactNavigationBar && navigationItem?.accessoryView == nil
case .alwaysHidden:
return false
}
}
private func updateSubtitleView(for navigationItem: UINavigationItem?) {
guard let navigationItem = navigationItem, navigationItem.titleView == nil, !usesLeadingTitle else {
return
}
let customTitleView = TwoLineTitleView(style: style == .primary ? .primary : .system)
customTitleView.tokenSet.setOverrides(from: tokenSet, mapping: [
.titleColor: .titleColor,
.titleFont: .titleFont,
.subtitleColor: .subtitleColor,
.subtitleFont: .subtitleFont
])
customTitleView.setup(navigationItem: navigationItem)
if navigationItem.titleAccessory == nil {
// Use default behavior of requesting an accessory expansion
customTitleView.delegate = self
}
navigationItem.titleView = customTitleView
}
// MARK: Content expansion/contraction
private var isExpanded: Bool = true
func expand(_ animated: Bool) {
isExpanded = true
titleView.expand(animated: animated)
guard barHeight != .contracted else {
return
}
let updateLayout = {
self.updateContentStackViewMargins(forExpandedContent: true)
}
if animated {
UIView.animate(withDuration: NavigationBar.expansionContractionAnimationDuration) {
updateLayout()
self.contentStackView.layoutIfNeeded()
}
} else {
updateLayout()
}
}
func contract(_ animated: Bool) {
isExpanded = false
titleView.contract(animated: animated)
guard barHeight != .expanded else {
return
}
let updateLayout = {
self.updateContentStackViewMargins(forExpandedContent: false)
}
if animated {
UIView.animate(withDuration: NavigationBar.expansionContractionAnimationDuration) {
updateLayout()
self.contentStackView.layoutIfNeeded()