我正在建立一个社交网络,允许用户通过查看他们关注的人从一个个人资料导航到下一个个人资料。为简单起见,我创建了一个包含两个视图控制器的测试项目:ViewController
和SecondViewController
。
每个视图控制器都有一个按钮,该按钮触发IBAction来实例化下一个视图控制器。然后将该视图推送到导航堆栈上。只要有另一个viewController要推送,用户就可以执行此操作。但是当他们开始返回/弹出时,就是我遇到问题了。
这是ViewController:
class ViewController: UIViewController {
@IBOutlet weak var pageNumberLabel: UILabel!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationItem.title = "First"
setUp()
}
func setUp() {
print("Setup 1")
let navBarAppearance = self.navigationController!.navigationBar
navBarAppearance.setBackgroundImage(UIImage(), for: .default)
navBarAppearance.shadowImage = UIImage()
navBarAppearance.barStyle = .black
navBarAppearance.isTranslucent = true
navBarAppearance.tintColor = .white
navBarAppearance.titleTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor.white]
self.navigationController?.view.backgroundColor = UIColor.lightGray
}
@IBAction func pushSecondViewController() {
if let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "secondVC") as? SecondViewController {
print("-")
self.navigationController?.pushViewController(vc, animated: true)
}
}
}
这是SecondViewController:
class SecondViewController: UIViewController {
@IBOutlet weak var pageNumberLabel: UILabel!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationItem.title = "Second"
setUp()
}
func setUp() {
print("Setup 2")
let navBarAppearance = self.navigationController!.navigationBar
navBarAppearance.isTranslucent = false
navBarAppearance.barTintColor = .white
navBarAppearance.tintColor = .blue
navBarAppearance.barStyle = .black
navBarAppearance.titleTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor.blue]
}
@IBAction func pushFirstViewController() {
if let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "firstVC") as? ViewController {
print("-")
self.navigationController?.pushViewController(vc, animated: true)
}
}
}
当弹出SecondViewController并显示ViewController时,navigationTitle保持UIColor.blue。但是,如果我从SecondViewController滑动到ViewController,标题会正确更改颜色。
这是为什么?
答案 0 :(得分:0)
我找到了针对此问题的解决方法...最初发布于here。我将以下代码放入导航栏的setUp()
函数中。
let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
titleView.backgroundColor = UIColor.clear
let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
titleLabel.textAlignment = .center
titleLabel.text = [My View Name]
titleLabel.textColor = .blue
titleView.addSubview(titleLabel)
self.navigationItem.titleView = titleView
self.navigationItem.title = [My View Name]