自定义 Navigation 样式

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
// MARK: Custom Navigation
struct NavigationBarColor: ViewModifier {

init(backgroundColor: UIColor, tintColor: UIColor, backColor: UIColor) {

let coloredAppearance = UINavigationBarAppearance()
coloredAppearance.configureWithOpaqueBackground()
coloredAppearance.backgroundColor = backgroundColor

// Inline Title 字体
let attrs1: [NSAttributedString.Key: Any] = [
.foregroundColor: tintColor,
.font: UIFont.monospacedSystemFont(ofSize: 24, weight: .black)
// .font: Font.system(size: 24, weight: .black, design: .monospaced) // 报错
]

// Large Title 字体
let attrs2: [NSAttributedString.Key: Any] = [
.foregroundColor: tintColor,
.font: UIFont.monospacedSystemFont(ofSize: 14, weight: .bold)
]

coloredAppearance.largeTitleTextAttributes = attrs1
coloredAppearance.titleTextAttributes = attrs2
//不要下面的线
coloredAppearance.shadowColor = .clear

// back 图片
let config = UIImage.SymbolConfiguration(font: .monospacedSystemFont(ofSize: 14, weight: .regular))
let backImage = UIImage(systemName: "chevron.backward", withConfiguration: config)?.withTintColor(backColor, renderingMode: .alwaysOriginal)
coloredAppearance.setBackIndicatorImage(backImage, transitionMaskImage: backImage)

// back 字体
let fontAttributes: [NSAttributedString.Key: Any] = [
.foregroundColor: backColor,
.font: UIFont.monospacedSystemFont(ofSize: 12, weight: .regular)
]

coloredAppearance.buttonAppearance.normal.titleTextAttributes = fontAttributes

UINavigationBar.appearance().standardAppearance = coloredAppearance
UINavigationBar.appearance().scrollEdgeAppearance = coloredAppearance
UINavigationBar.appearance().compactAppearance = coloredAppearance
}

func body(content: Content) -> some View {
content
}
}

//配合上面
extension View {
func navigationBarColor(backgroundColor: UIColor, tintColor: UIColor, backColor: UIColor) -> some View {
self.modifier(NavigationBarColor(backgroundColor: backgroundColor, tintColor: tintColor, backColor: backColor))
}
}

使用:

1
2
3
4
NavigationView {
...
}
.navigationBarColor(backgroundColor: UIColor(.blue), tintColor: UIColor(Color(.black), backColor: UIColor(.pink))

自定义 Navigation 样式
https://wonderhoi.com/2024/11/06/自定义-Navigation-样式/
作者
wonderhoi
发布于
2024年11月6日
许可协议