【问题标题】:Change Navigation bar title index colour with Color Set in Assets使用资产中的颜色集更改导航栏标题索引颜色
【发布时间】:2020-12-11 20:16:26
【问题描述】:

我必须将导航栏标题的最后 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]
    }
}

【问题讨论】:

    标签: swift swiftui uinavigationbar navigationbar uinavigationbarappearance


    【解决方案1】:

    我这样做的一种方法是将根视图添加到 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)
                }
            }
        }
        
    }
    

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

    【讨论】:

    • 这并不能解决我的问题,但我希望它对只使​​用内联显示模式的人有所帮助。对于我的具体情况,我正在寻找一种简单的方法来改变导航栏的外观
    【解决方案2】:

    如果你想用自定义颜色为字符串的最后五个字母着色,你可以使用这种方法:

    string.addAttribute(NSAttributedString.Key.foregroundColor, value: Color("orange1"), range: NSMakeRange(string.length-5, 5))
    

    我不确定你如何使用 UINavigationBar.appearance().titleTextAttributes 语法,但也许这对你有帮助

    【讨论】:

    • 这就是问题所在,在普通字符串中我可以做到这一点,但我不知道如何在 UINavigationBar 中做到这一点
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-05
    • 2023-03-19
    • 2018-02-06
    相关资源
    最近更新 更多