首页 > 解决方案 > 使用资产中的颜色集更改导航栏标题索引颜色

问题描述

我必须将导航栏标题的最后 5 个字母更改为资产中的颜色。

struct MainView: View {
    var body: some View {
        NavigationView {
            Text("Hello, World!")
            
            .navigationBarTitle("HelloWorld")
        }
    }
    
    init() {
        // UIColor.red should be Color("orange1") and only for the last 5 letters (World)
        UINavigationBar.appearance().largeTitleTextAttributes = [.foregroundColor: UIColor.red]
        UINavigationBar.appearance().titleTextAttributes = [.foregroundColor: UIColor.red]
    }
}

标签: swiftswiftuiuinavigationbarnavigationbaruinavigationbarappearance

解决方案


我这样做的一种方法是将根视图添加到顶部对齐的 ZStack 中,并在根视图之后添加自定义中心视图。然后,我只是将文本放在 HStack 中,并获得您想要的标题的前缀和后缀,并将颜色更改为您想要的任何颜色。有不同的方法可以解决这个问题,但这就是我为这个例子选择的方法。最终结果看起来像这样。

var navBarTitle: String = "HelloWorld"
var body: some View {
    ZStack(alignment: .top){
        //Root view with empty Title
        NavigationView {
            Text("Hello, World")
                .navigationBarTitle("",displayMode: .inline)
        }
        
        VStack{
            HStack{
                Text(navBarTitle.prefix(5))
                    .font(.largeTitle)
                    .foregroundColor(.red)
                Text(navBarTitle.suffix(5))
                    .font(.largeTitle)
                    .foregroundColor(.blue)
            }
        }
    }
    
}

在此处输入图像描述

不确定这是否正是您要寻找的,但希望对您有所帮助!


推荐阅读