swift - 如何在从 firebase 获取值时更改 NavBar 标题颜色

标签 swift firebase firebase-realtime-database uinavigationcontroller

我正在使用 Bool 从 Firebase 获取在线状态。获取值时,导航栏标题颜色应根据离线或在线状态更改为绿色或黑色。

但是,当我得到它当前正在更改标题的值时,但只有在按下后退按钮后,导航栏标题颜色才会执行颜色更改。 (我想在当前 View 上立即更新,而不是在按下后退时,顺便说一下,整个层次结构正在更改,我只想更改该 View 的当前标题。

ViewDidLoad 调用

swift 5、火力地堡 6

func fetchOnlineStatus() {
        let navBar = self.navigationController?.navigationBar
        DB_REF.child("Users").child(user?.uid ?? "").child("online").observe(DataEventType.value) { (snapshot) in
            let postDict = snapshot.value as? Bool
            if postDict == true {
                    navBar?.titleTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.green]
                        navBar?.setNeedsDisplay()
                        navBar?.layoutIfNeeded()
                        navBar?.setNeedsDisplay()
                        self.collectionView.reloadData()
                        self.collectionView.setNeedsDisplay()
                        self.collectionView.layoutIfNeeded()
            } else {
                print("false")
                let changeColor = [NSAttributedString.Key.foregroundColor:UIColor.black]
                self.navigationController?.navigationBar.titleTextAttributes = changeColor
            }
        }
    }

最佳答案

尝试在主线程上更改 NavBar 标题颜色:

 DispatchQueue.main.async {
    navBar?.titleTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.green]
    navBar?.setNeedsDisplay()
    navBar?.layoutIfNeeded()
    navBar?.setNeedsDisplay()
 }

关于swift - 如何在从 firebase 获取值时更改 NavBar 标题颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56142223/

相关文章:

java - 为什么我们需要一个空的构造函数来传递/保存来自 Firebase 的数据?

swift - 使用 double 对 UITableView 进行排序

ios - 无法在 iOS 中同时使用 Urban Airship 和 Facebook 云消息传递

android - Firebase:报告分析和崩溃数据以分离项目

javascript - Firebase UID 是否始终为 28 个字符?

swift - 使用 ActionSheet 中的 Collection View 显示照片

android - Firebase RecyclerView 未加载新数据

swift - 单击按钮后更改 label.text

swift - Daniel Gindi 图表库 : Draw the value label only for the highlighted bar

swift - 向按钮添加操作,该按钮通过快速扩展添加到文本字段