我找到了您遇到此问题的原因。这是因为名称为_UINavigationBarContentView 的私有视图。这是UINavigationBar 的子视图。 navigationItem.titleView 包含在此视图中。
第一次,当你改变navigationItem.titleView。 _UINavigationBarContentView.clipsToBounds 是 false 。但是在你推动另一个控制器并弹回之后,_UINavigationBarContentView.clipsToBounds 是 true。这就是 titleView 被裁剪的原因。
所以我有一个临时解决方案。每次出现viewController,找到这个视图,把_UINavigationBarContentView.clipsToBounds改成false,布局titleView。
override func viewDidAppear(_ animated: Bool) {
for view : UIView in (navigationController?.navigationBar.subviews)! {
view.clipsToBounds = false;
}
navigationItem.titleView?.layoutIfNeeded()
}
override func viewWillAppear(_ animated: Bool) {
for view : UIView in (navigationController?.navigationBar.subviews)! {
view.clipsToBounds = false;
}
navigationItem.titleView?.layoutIfNeeded()
}
我试过了,效果很好。但我认为你不应该这样做,因为它是私人观点。也许 Apple 不希望我们对它做任何事情。
希望我的建议能对你有所帮助。祝你好运;)
解决方案
为_UINavigationBarContentView.clipsToBounds添加观察者,每次更改为false时,设置为true并更新titleView的布局
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let logo = UIImage(named: "Logo")
let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 60, height: 60))
let imageView = UIImageView(image: logo)
imageView.frame = CGRect(x: 0, y: 0, width: titleView.frame.width, height: titleView.frame.height)
titleView.addSubview(imageView)
imageView.contentMode = .scaleAspectFit
imageView.image = logo
navigationItem.titleView = titleView
navigationController?.navigationBar.subviews[2].addObserver(self, forKeyPath: "clipsToBounds", options: [.old, .new], context: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if (navigationController?.navigationBar.subviews[2].isEqual(object))! {
DispatchQueue.main.async {
self.navigationController?.navigationBar.subviews[2].clipsToBounds = false
self.navigationItem.titleView?.layoutIfNeeded()
}
}
}
deinit {
navigationController?.navigationBar.subviews[2].removeObserver(self, forKeyPath: "clipsToBounds")
}
更多细节和更简单,你可以在这里查看我的演示https://github.com/trungducc/stackoverflow/tree/big-title-navigation-bar