KVISH KVISH - 1 month ago 14
iOS Question

Increase NavigationBar height

I have the following code:

func navbarbutton() {
UIView.animateWithDuration(0.2, animations: { () -> Void in
let current = self.navigationController?.navigationBar.frame
self.navigationController?.navigationBar.frame = CGRectMake(self.frame!.origin.x, self.frame!.origin.y, self.frame!.size.width, current!.size.height + 50)
self.navigationController?.navigationBar.layoutIfNeeded()
})
}


I'm able to increase the height of the navigation bar by 50 dp. That's not the issue for me. The issue I'm having is that the
UIBarButtonItems
are all aligned to the bottom. How can I get them aligned to the top so that I can add more to the bottom myself? I'm getting something as per the image:

enter image description here

Is it possible to get it aligned to the top?

Joe Joe
Answer

Try this code:

Note: Code tested in Swift 3.

Answer 1: Updated Answer

class ViewController: UIViewController {

var customBar: UINavigationBar = UINavigationBar()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    //Title
    title = "Some Title"

    // Add bar button item
    navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Add", style: .plain, target: self, action:  #selector(addTapped))
    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Back", style: .plain, target: self, action: #selector(addTapped))

    self.customBar.frame = CGRect(x:0, y:0, width:view.frame.width, height:(navigationController?.navigationBar.frame.height)! + 50)  
    self.customBar.backgroundColor = UIColor.green
    self.view.addSubview(customBar)
}

func addTapped() {

    print("Button Pressed")

}

Output:

enter image description here


Answer 2:

override var isViewLoaded: Bool {

    // Add bar button item
    navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Add", style: .plain, target: self, action:  #selector(addTapped))
    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Back", style: .plain, target: self, action: #selector(addTapped))

    //Vertical and Horizonal barButtonItem position offset
    navigationItem.leftBarButtonItem?.setTitlePositionAdjustment(UIOffset(horizontal: 0, vertical: 20), for: UIBarMetrics.default)

    navigationItem.rightBarButtonItem?.setTitlePositionAdjustment(UIOffset(horizontal: 0, vertical: 20), for: UIBarMetrics.default)

    return true
}

func addTapped() {

    print("Button Pressed")

}

Note: Above code only works in isViewLoaded: Bool method.But, No luck.When, I tried this code in other viewLoad method.

Output 1: barButtonItem moved 20 pixel up vertically.

enter image description here

Output 2: barButtonItem moved 20 pixel down vertically.

enter image description here

Hope, Above code fix your problem.

Comments