2016-09-15 42 views
0

我有兩個ViewControllers。我想在導航欄上添加一個UIViewPush Segue後添加UIView在導航欄上

我可以通過創建一個UINavigationItem出口以及將所述的UIView編程創建到UINavigationItem出口titleview的在第一導航欄的頂部添加的UIView

代碼片段(HomeVC - 拳套的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. 
} 
} 

截圖景觀:

enter image description here

現在櫃面SecondVC的我試圖做推後,同樣的事情塞格。

代碼片段(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. 
} 
} 

截圖詳情查看:

enter image description here

故事板截圖:

Storyboard Screenshot

視圖層次:

View Hierarchy

注:我特意指派的Y位置到視圖大於0,以確保正在創建

的看法,但因爲我不能創建一個UINavigationItem,我將以編程方式創建的視圖添加到視圖中,甚至試圖將子視圖放在前面。

注:是的,UINavigationBar的的尺寸已經增大,請參考這裏:Change width/height UINavigationBar embedded in a Navigation Controller

回答

0

你可以使用UIViewController

public var navigationItem: UINavigationItem { get } 

從定義的變量文檔:

按需創建,以便視圖控制器可以自定義其導航外觀。

所以在viewDidLoadUIViewController每個子類你可以做

self.navigationItem.titleView = navBarView