在self中添加导航栏
Add navigation bar within self
我想在 UIViewController
中添加 UINavigationBar
。我知道我可以在 故事板 中添加一个 导航栏 我也可以使用 segue 触发它,也可以通过添加 宽度和高度。我不想手动执行,而是想在 class 内部执行,而不添加 height 和 width。 导航栏 表现自然,就好像它是由 segue 触发的一样。所以像 self.navigationController
这样的东西会起作用。 self.navigationController
会呈现 UINavigationBar
以及我需要添加的任何其他内容。
将此代码用于 swift2.X 用于 swift3 使用此 link Adding Navigation Bar programmatically iOS
// Create the navigation bar
let navigationBar = UINavigationBar(frame: CGRectMake(0, 0, self.view.frame.size.width, 44)) // Offset by 20 pixels vertically to take the status bar into account
navigationBar.backgroundColor = UIColor.whiteColor()
navigationBar.delegate = self;
// Create a navigation item with a title
let navigationItem = UINavigationItem()
navigationItem.title = "Title"
// Create left and right button for navigation item
let leftButton = UIBarButtonItem(title: "Save", style: UIBarButtonItemStyle.Plain, target: self, action: "btn_clicked:")
let rightButton = UIBarButtonItem(title: "Right", style: UIBarButtonItemStyle.Plain, target: self, action: nil)
// Create two buttons for the navigation item
navigationItem.leftBarButtonItem = leftButton
navigationItem.rightBarButtonItem = rightButton
// 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)
func btn_clicked(sender: UIBarButtonItem) {
// Do something
}
我想在 UIViewController
中添加 UINavigationBar
。我知道我可以在 故事板 中添加一个 导航栏 我也可以使用 segue 触发它,也可以通过添加 宽度和高度。我不想手动执行,而是想在 class 内部执行,而不添加 height 和 width。 导航栏 表现自然,就好像它是由 segue 触发的一样。所以像 self.navigationController
这样的东西会起作用。 self.navigationController
会呈现 UINavigationBar
以及我需要添加的任何其他内容。
将此代码用于 swift2.X 用于 swift3 使用此 link Adding Navigation Bar programmatically iOS
// Create the navigation bar
let navigationBar = UINavigationBar(frame: CGRectMake(0, 0, self.view.frame.size.width, 44)) // Offset by 20 pixels vertically to take the status bar into account
navigationBar.backgroundColor = UIColor.whiteColor()
navigationBar.delegate = self;
// Create a navigation item with a title
let navigationItem = UINavigationItem()
navigationItem.title = "Title"
// Create left and right button for navigation item
let leftButton = UIBarButtonItem(title: "Save", style: UIBarButtonItemStyle.Plain, target: self, action: "btn_clicked:")
let rightButton = UIBarButtonItem(title: "Right", style: UIBarButtonItemStyle.Plain, target: self, action: nil)
// Create two buttons for the navigation item
navigationItem.leftBarButtonItem = leftButton
navigationItem.rightBarButtonItem = rightButton
// 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)
func btn_clicked(sender: UIBarButtonItem) {
// Do something
}