在self中添加导航栏

时间:2016-09-21 12:48:30

标签: ios swift uiviewcontroller uinavigationbar

我希望在 UINavigationBar 中添加 UIViewController 。我知道我可以在 Storyboard 中添加导航栏,我也可以使用segue触发它,并通过添加宽度手动执行和身高。我不想手动操作,而是想在课堂内完成,而不添加高度宽度导航栏的行为自然就像是由segue触发。那么像 self.navigationController 这样的东西就可以了。 self.navigationController 会显示 UINavigationBar

我需要添加任何其他内容。

1 个答案:

答案 0 :(得分:0)

将此代码用于swift2.X for swift3使用此链接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
 }