NavigationBar标题不会出现

问题描述 投票:3回答:2

我以编程方式添加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"

什么也没有

ios iphone swift uinavigationbar titlebar
2个回答
8
投票

希望这会帮助你。

// 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)

0
投票

导航栏标题在显示的视图控制器中设置。通常这是在视图中完成视图控制器上的加载:

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

编辑:在意识到OP正在将UINavigationBar添加到UIViewController而不使用标准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)
© www.soinside.com 2019 - 2024. All rights reserved.