我有两个 ViewControllers 。我想在导航栏上添加 UIView 。
我可以在第一个导航栏的顶部添加 UIView ,方法是创建一个 UINavigationItem 插件,然后以编程方式将 UIView 添加到< strong> UINavigationItem outlet titleView 。
Code Snippet(HomeVC - Fist ViewController):
class HomeVC: UIViewController {
@IBOutlet weak var homeNavigationItem: UINavigationItem!
let navBarView = UIView()
let topNavBarLabel = UILabel()
let screenWidth = UIScreen.main.bounds.width
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
navBarView.frame = CGRect(x: 0.0, y: 0.0, width: screenWidth, height: 50.0)
topNavBarLabel.text = "Hello World"
topNavBarLabel.textAlignment = NSTextAlignment.center
topNavBarLabel.textColor = UIColor.white
topNavBarLabel.frame = CGRect(x: 0.0, y: 10.0, width: screenWidth, height: 20.0)
navBarView.addSubview(topNavBarLabel)
homeNavigationItem.titleView = navBarView
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
屏幕截图主页视图:
现在加入SecondVC我试图在推送 Segue之后做同样的事情。
代码片段(DetailVC - 第二个ViewController):
class DetailsVC: UIViewController {
let navBarView = UIView()
let screenWidth = UIScreen.main.bounds.width
let navBarTopLabel = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
navBarView.frame = CGRect(x: 0.0, y: 50.0, width: screenWidth, height: 50.0)
navBarView.backgroundColor = UIColor.black
navBarTopLabel.frame = CGRect(x: 0.0, y: 10.0, width: screenWidth, height: 20.0)
navBarTopLabel.textColor = UIColor.white
navBarTopLabel.text = "Details Hello"
navBarTopLabel.textAlignment = NSTextAlignment.center
navBarView.addSubview(navBarTopLabel)
self.view.addSubview(navBarView)
self.view.bringSubview(toFront: navBarView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
屏幕截图详情查看:
故事板截图:
查看层次结构:
注意:我故意为视图分配的Y位置大于0,以确保正在创建视图
但由于我无法创建 UINavigationItem ,我将以编程方式创建的视图添加到视图中,甚至尝试将 subView 添加到前端。
注意:是的, UINavigationBar 的大小已增加,请参阅此处:Change width/height UINavigationBar embedded in a Navigation Controller
答案 0 :(得分:0)
您可以使用为UIViewController
public var navigationItem: UINavigationItem { get }
来自文档:
按需创建,以便视图控制器可以自定义其导航外观。
因此,UIViewController
中viewDidLoad
的每个子类都可以执行
self.navigationItem.titleView = navBarView