我正在使用 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/