Create NavBar programmatically with Button and Title Swift

前端 未结 2 1486
猫巷女王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)
    

提交回复
热议问题