Create NavBar programmatically with Button and Tit

2019-03-09 19:56发布

问题:

I try to create a NavBar, so far the NavBar is no problem but if i try to add buttons and the title i get sucked.

My NavBar look like

let NameHeight = screenHeight * 0.09
let NameWidth = screenWidth
let navBar: UINavigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: NameWidth, height: NameHeight))
self.view.addSubview(navBar)

so i try to set my NavBar title like

navigationBar.topItem.title = "some title"
or
navigationBar.title = "some title"

but both fail.
Also if i try to set a button

let btnName = UIButton()
btnName.setImage(UIImage(named: "imagename"), forState: .Normal)
btnName.frame = CGRectMake(0, 0, 30, 30)
btnName.addTarget(self, action: Selector("action"), forControlEvents: .TouchUpInside)

//.... Set Right/Left Bar Button item
let rightBarButton = UIBarButtonItem()
rightBarButton.customView = btnName
self.navigationItem.rightBarButtonItem = rightBarButton

this does not give me a error but the button is simply not displayed

回答1:

Updated for Swift 4

You must 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 = UINavigationBar(frame: CGRect(x: 0, y: 0, width: 320, height: 44))
self.view.addSubview(navBar);

let navItem = UINavigationItem(title: "SomeTitle");
let doneItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.done, target: nil, action: #selector("selectorName"));
navItem.rightBarButtonItem = doneItem;

navBar.setItems([navItem], animated: false);


回答2:

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

}