【问题标题】:Setting UIBarButtonItem appearance resulted in weird behaviour with back button设置 UIBarButtonItem 外观会导致后退按钮出现奇怪的行为
【发布时间】:2025-12-08 07:55:02
【问题描述】:
        let attributes = [
            NSAttributedString.Key.foregroundColor: UIColor.orange,
            NSAttributedString.Key.font: UIFont.systemFont(ofSize: 22)
        ]
        // set nav bar button item
        // solution 1 - this will not work properly.
        // refer to the Imgur 
        UINavigationBar.appearance().titleTextAttributes = attributes
        UIBarButtonItem.appearance(whenContainedInInstancesOf: [UINavigationBar.self]).setTitleTextAttributes(attributes, for: .normal)
        
        // 
        // solution 2: this works fine
        let app = UIBarButtonItemAppearance()
        app.normal.titleTextAttributes = attributes
        
        let navBarApp = UINavigationBarAppearance()
        navBarApp.configureWithOpaqueBackground()
        navBarApp.buttonAppearance = app
        UINavigationBar.appearance().standardAppearance = navBarApp

我不确定为什么 solution 1 不能完全工作,但我认为问题与 UIBarButtonItem.appearance(whenContainedInInstancesOf: [UINavigationBar.self]).setTitleTextAttributes(attributes, for: .normal) 这一行有关。这不是为 navBar 和 BarButtonItem 设置外观和样式(字体/颜色/等)的正确方法吗?

解决方案 2 工作正常,所以我不打算附加任何内容。

编辑:看起来链接已过期。这是解决方案 1 的新链接:https://imgur.com/a/DJAzrSw

【问题讨论】:

    标签: swift uikit uinavigationbar uibarbuttonitem uiappearance


    【解决方案1】:

    我设法解决了解决方案 1 的问题,但老实说,我不知道为什么我需要 normalhighlighted 状态才能正常工作。

    需要添加以下内容

    UIBarButtonItem.appearance(whenContainedInInstancesOf: [UINavigationBar.self]).setTitleTextAttributes(attributes, for: .highlighted)
    

    【讨论】: