我有两个视图控制器VC1和VC2,首先,我展示VC1并以编程方式创建导航栏,并在其中放置两个按钮,此后,我展示VC2并以编程方式创建导航栏。现在,当我将VC2更改为VC1时,它会将视图削减到导航栏的一半,并且按钮也会被切除。我尝试了不同的解决方案,但没有解决。我很困惑为什么要削减视野?这是我的代码,用于在VC1中创建导航栏,
let width = self.view.frame.width
let navigationBar: UINavigationBar = UINavigationBar(frame: CGRect(x: 0, y: 20, width: width, height: 64))
UINavigationBar.appearance().barTintColor = .white
UINavigationBar.appearance().tintColor = .white
UINavigationBar.appearance().isTranslucent = false
self.view.addSubview(navigationBar);
let navigationItem = UINavigationItem(title: "Owners")
self.title = "Owners"
let cancelBtn = UIButton()
let searchBtn = UIButton()
cancelBtn.setImage(UIImage.init(named: "cancelBtn")?.tint(with: #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)), for: .normal)
cancelBtn.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
cancelBtn.addTarget(self, action: #selector(onTapBack), for: .touchUpInside)
let suggestButtonContainer = UIView(frame: cancelBtn.frame)
suggestButtonContainer.addSubview(cancelBtn)
searchBtn.setImage(Icon.cm.search?.tint(with: #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)), for: .normal)
searchBtn.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
searchBtn.addTarget(self, action: #selector(onTapSearch), for: .touchUpInside)
let searchView = UIView(frame: searchBtn.frame)
searchView.addSubview(searchBtn)
let searchButtonItem = UIBarButtonItem(customView: searchView)
let suggestButtonItem = UIBarButtonItem(customView: suggestButtonContainer)
navigationItem.leftBarButtonItem = suggestButtonItem
navigationItem.rightBarButtonItem = searchButtonItem
navigationBar.setItems([navigationItem], animated: false)
这就是我创建VC2导航栏的方式,
let width = self.view.frame.width
let navigationBar: UINavigationBar = UINavigationBar(frame: CGRect(x: 0, y: 25, width: width, height: 64))
UINavigationBar.appearance().barTintColor = .white
UINavigationBar.appearance().tintColor = .white
UINavigationBar.appearance().isTranslucent = false
self.view.addSubview(navigationBar);
let navigationItem = UINavigationItem(title: "Owners")
self.title = "Owners"
let cancelBtn = UIButton()
cancelBtn.setImage(UIImage.init(named: "cancelBtn")?.tint(with: #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)), for: .normal)
cancelBtn.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
cancelBtn.addTarget(self, action: #selector(onTapBack), for: .touchUpInside)
let suggestButtonContainer = UIView(frame: cancelBtn.frame)
suggestButtonContainer.addSubview(cancelBtn)
let suggestButtonItem = UIBarButtonItem(customView: suggestButtonContainer)
navigationItem.leftBarButtonItem = suggestButtonItem
navigationBar.setItems([navigationItem], animated: false)
我认为问题出在状态栏高度。
尝试将导航栏框架origin.y
设置为UIApplication.shared.statusBarFrame.height
let navigationBar: UINavigationBar = UINavigationBar(frame: CGRect(x: 0, y: UIApplication.shared.statusBarFrame.height, width: width, height: 64))