我在iOS导航栏中的titleView遇到问题。我已经为titleView创建了一个自定义视图,但是每当我按下另一个控制器时,当我回到第一个视图控制器时,titleView就会立即出现并消失。这是我的代码。
override func viewDidLoad() {
super.viewDidLoad()
let logo = UIImage(named: "img_appbar_logo")?.withRenderingMode(UIImageRenderingMode.alwaysTemplate)
logoContainer = UIView(frame: CGRect(x: 0, y: 0, width: 180, height: 40))
logoContainer.backgroundColor = UIColor.clear
animatedLogo = UIImageView(frame: CGRect(x: 0, y: 0, width: logoContainer.frame.width, height: logoContainer.frame.height))
animatedLogo.contentMode = .scaleAspectFit
animatedLogo.clipsToBounds = true
animatedLogo.image = logo
logoContainer.addSubview(animatedLogo)
navigationItem.titleView = logoContainer
}
答案 0 :(得分:0)
在titleWillAppear中设置titleView,因为titleView被以前的控制器中的标题替换了
答案 1 :(得分:0)
我已经解决了导航栏中与titleView有关的问题。我发现在按下另一个控制器并弹出后,titleView将被NavigationItem中的空UILabel视图取代。这就是titleView出现然后消失的原因。
我如何解决此问题?
我将自定义视图直接添加到导航栏中。这是代码
let logo = UIImage(named: "img_appbar_logo")?.withRenderingMode(UIImageRenderingMode.alwaysTemplate)
logoContainer = UIView(frame: CGRect(x: 0, y: 0, width: 180, height: 40))
logoContainer.backgroundColor = UIColor.red
animatedLogo = UIImageView(frame: CGRect(x: 0, y: logoContainer.frame.origin.y, width: logoContainer.frame.width, height: logoContainer.frame.height))
animatedLogo.contentMode = .scaleAspectFit
animatedLogo.clipsToBounds = true
animatedLogo.image = logo
logoContainer.addSubview(animatedLogo)
navigationController?.navigationBar.addSubview(logoContainer) <--- new
//navigationItem.titleView = logoContainer <---- old
然后删除viewWillDisappear上的视图
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
logoContainer.removeFromSuperview()
}