首页 > 解决方案 > 设置 UIBarButtonItem 外观会导致后退按钮出现奇怪的行为

问题描述

        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

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

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

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

标签: swiftuikituinavigationbaruibarbuttonitemuiappearance

解决方案


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

需要添加以下内容

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

推荐阅读