Create NavBar programmatically with Button and Title Swift

前端 未结 2 1442
猫巷女王i
猫巷女王i 2021-02-01 02:53

I try to create a NavBar, so far the NavBar is no problem but when I try to add the buttons and title, they don\'t get displayed

My NavBar look like

let          


        
相关标签:
2条回答
  • 2021-02-01 03:50

    Updated for Swift 5

    Create a navigation item instance and set title and right/left buttons to it. After navigation item is configured add it to the navigation bar.

    let navBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: 44))
    view.addSubview(navBar)
    
    let navItem = UINavigationItem(title: "SomeTitle")
    let doneItem = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(selectorName:))
    navItem.rightBarButtonItem = doneItem
    
    navBar.setItems([navItem], animated: false)
    
    0 讨论(0)
  • 2021-02-01 03:52

    Basically azimov's answer in Swift 4

    override func viewDidLoad() {
        super.viewDidLoad()
        self.setNavigationBar()
    }
    
    func setNavigationBar() {
        let screenSize: CGRect = UIScreen.main.bounds
        let navBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: screenSize.width, height: 44))
        let navItem = UINavigationItem(title: "")
        let doneItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.done, target: nil, action: #selector(done))
        navItem.rightBarButtonItem = doneItem
        navBar.setItems([navItem], animated: false)
        self.view.addSubview(navBar)
    }
    
    @objc func done() { // remove @objc for Swift 3
    
    }
    
    0 讨论(0)
提交回复
热议问题