簡體   English   中英

NavigationBar標題不會出現

[英]NavigationBar title doesn't appear

我以編程方式添加NavigationBar,后來又添加了標題,但它根本沒有出現。 這里有什么問題?

let navigationBar = UINavigationBar(frame: CGRectMake(0, 0, self.view.frame.size.width, 55))
navigationBar.barTintColor = UIColor(red: 44/255, green: 54/255, blue: 63/255, alpha: 1)
navigationController?.navigationItem.title = "AAA"
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.whiteColor()]
view.addSubview(navigationBar)

導航欄出現,但標題不是。 怎么解決?

我也試過這個:

navigationBar.topItem?.title = "BBB"

什么也沒有

希望這會幫助你。

// Create the navigation bar
let navigationBar = UINavigationBar(frame: CGRectMake(0, 0, self.view.frame.size.width, 64)) 

// Offset by 20 pixels vertically to take the status bar into account

navigationBar.backgroundColor = UIColor.whiteColor()

// Create a navigation item with a title
let navigationItem = UINavigationItem()
    navigationItem.title = "Title"

// Assign the navigation item to the navigation bar
navigationBar.items = [navigationItem]

// Make the navigation bar a subview of the current view controller
self.view.addSubview(navigationBar)

這段代碼對我有用。

更新:Swift 4 / Swift 5

// Create the navigation bar
let navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 64))

// Offset by 20 pixels vertically to take the status bar into account

navigationBar.backgroundColor = UIColor.white

// Create a navigation item with a title
let navigationItem = UINavigationItem()
navigationItem.title = "Title"

// Assign the navigation item to the navigation bar
navigationBar.items = [navigationItem]

// Make the navigation bar a subview of the current view controller
self.view.addSubview(navigationBar)

導航欄標題在顯示的視圖控制器中設置。 通常這是在視圖中完成視圖控制器上的加載:

override func viewDidLoad() {
    super.viewDidLoad()
    self.title = "AAA"
}

編輯:在意識到OP正在向UIViewController添加UINavigationBar而不使用標准UINavigationController

let navigationBar = UINavigationBar(frame: CGRectMake(0, 0, self.view.frame.size.width, 55))
navigationBar.barTintColor = UIColor(red: 44/255, green: 54/255, blue: 63/255, alpha: 1)
let navigationItem = UINavigationItem.init(title: "AAA")
navigationBar.items = [navigationItem]
view.addSubview(navigationBar)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM