【发布时间】:2016-09-15 08:34:27
【问题描述】:
我有两个 ViewControllers。我想在导航栏上添加一个 UIView。
我可以通过创建一个 UINavigationItem Outlet 并将以编程方式创建的 UIView 添加到 UIView 到第一个导航栏的顶部strong>UINavigationItem 出口 titleView。
代码片段(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,我正在尝试在 Push 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.
}
}
截图详情查看:
故事板截图:
查看层次结构:
注意:我特意为视图分配了一个大于 0 的 Y 位置,以确保正在创建视图
但由于我无法创建 UINavigationItem,因此我将通过编程方式创建的视图添加到视图中,甚至尝试将 subView 置于最前面。
注意:是的,UINavigationBar的大小已经增加,请参考这里:Change width/height UINavigationBar embedded in a Navigation Controller
【问题讨论】:
标签: ios swift uiview uinavigationbar uinavigationitem