Adding Navigation Bar programmatically iOS

前端 未结 5 2138
你的背包
你的背包 2020-11-29 03:48

I am trying to make an App with a Navigation Bar (Back button, title, etc) and a Tab Bar (Toolbar on the bottom). I am using subviews so I don\'t have to worry about the sta

5条回答
  •  死守一世寂寞
    2020-11-29 04:18

    Swift 5.

    The context: Here is a view controller that is presented to edit a user's bio information.

    import UIKit
    
    class EditBioController: UIViewController {
    
        // What you need are these two classes. One is a navigation bar,
        // and the other will hold the items that are in the navigation bar.
        private var navigationBar: UINavigationBar!
        private var customNavigationItem: UINavigationItem!
        
        override func viewDidLoad() {
            super.viewDidLoad()
            // Create a navigation bar with the width of the view, and the standard height of 44.
            navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 44))
            
            // Initialize the UINavigationItem class. The name is a bit confusing, because as you'll see -
            // we add multiple items to the one 'UINavigationItem.'
            customNavigationItem = UINavigationItem()
            customNavigationItem.title = "Edit Bio"
            
            let leftBarButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(selectorX))
            customNavigationItem.leftBarButtonItem = leftBarButton
            
            let rightBarButton = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(selectorX))
            customNavigationItem.rightBarButtonItem = rightBarButton
            
            // Add the items to the navigation bar.
            navigationBar.items = [customNavigationItem]
            // Add the navigation bar to the view.
            self.view.addSubview(navigationBar)
            
            
        }
        
        @objc func selectorX() {
            
        }
        
    }
    

    Here's what this produces:

提交回复
热议问题