iOS导航栏标题不显示(标题颜色设置失效)技术求助
问题解决:导航栏标题不显示的修复方案
核心问题定位
你代码里错误地将标题赋值给了navigationController?.navigationItem,但导航栏实际显示的是当前视图控制器自身navigationItem的标题,而非导航控制器的navigationItem,这是标题不显示的直接原因。
修复步骤
修正标题赋值对象
将:navigationController?.navigationItem.title = "Add Personal Finance Log"修改为:
navigationItem.title = "Add Personal Finance Log"潜在问题排查(可选)
- 确认
APP_FONT_MAIN对应的字体已正确导入项目,若字体不存在,可临时替换为系统字体测试:UIFont.systemFont(ofSize: 22) - 检查
hexStringToUIColor方法是否正确返回预期的绿色背景色,避免因背景色与标题色一致导致标题被“隐藏”(此场景概率较低,可作为兜底排查项)
- 确认
修复后的完整代码片段
func configureUI() { view.backgroundColor = .white //configure NavBar navigationItem.title = "Add Personal Finance Log" navigationController?.navigationBar.isHidden = false navigationController?.navigationItem.hidesBackButton = true let backButton = UIBarButtonItem(image: UIImage(systemName: "chevron.left")?.withTintColor(.white, renderingMode: .alwaysOriginal), style: .plain, target: self, action: #selector(handleBack)) navigationItem.leftBarButtonItem = backButton let appearance = UINavigationBarAppearance() appearance.configureWithOpaqueBackground() appearance.backgroundColor = hexStringToUIColor(hex: APP_HEXCOLOR_MAIN) let titleAttribute = [NSAttributedString.Key.font: UIFont.init(name: APP_FONT_MAIN, size: 22), NSAttributedString.Key.foregroundColor: UIColor.white] appearance.titleTextAttributes = titleAttribute as [NSAttributedString.Key : Any] navigationItem.standardAppearance = appearance navigationItem.scrollEdgeAppearance = appearance navigationItem.compactAppearance = appearance }
内容的提问来源于stack exchange,提问作者ohu
相关产品推荐
相关产品推荐

