3

There is extra padding top when my app in landscape. Here is my code when create navigation bar programmatically. Any advice to remove the padding top when in landscape mode?

    let navigationBar = UINavigationBar(frame: CGRectMake(0, 0, self.view.frame.size.width, 44)

    navigationBar.backgroundColor = UIColor.redColor()
    navigationBar.delegate = self;

    let navigationItem = UINavigationItem()
    navigationItem.title = "Title"

    let btnLeft = UIButton(frame: CGRectMake(0, 0, 44, 44))
    btnLeft.setImage(UIImage(named: “myImage.png"), forState: .Normal)

    let leftButton =  UIBarButtonItem()
    leftButton.customView = btnLeft

    navigationItem.leftBarButtonItem = leftButton

    navigationBar.items = [navigationItem]

    self.view.addSubview(navigationBar)

Snapshot from simulator (Landscape)

enter image description here

Snapshot from simulator (Portrait)

enter image description here

kaneyip
  • 1,237
  • 1
  • 17
  • 21

1 Answers1

0

You should easily solve with this setting (in your viewDidLoad for example):

self.edgesForExtendedLayout = UIRectEdge.None

Alternative: You can put it also in your UINavigationController delegate method (if you have setted in your class your navigation delegate UINavigationControllerDelegate ) called willShowViewController:

func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) {
    viewController.edgesForExtendedLayout = UIRectEdge.None
}

If you work with UITableView you may also to do:

 self.automaticallyAdjustsScrollViewInsets = false

You can also edit directly to the attribute inspector:

enter image description here

If anyone of these approaches don't work, by default your UINavigationBar have different heights based on your orientation. For example, the navigation bar is 44 points in portrait and 32 points in landscape. A workaround can be:

// Create an IBOutlet of your navigationBar height constraint
@IBOutlet weak var navBarHeight: NSLayoutConstraint

override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        if self.view.bounds.size.height > self.view.bounds.size.width {
            self.navBarHeight.constant = 44
        } else {
            self.navBarHeight.constant = 32
        }
}
Alessandro Ornano
  • 34,887
  • 11
  • 106
  • 133
  • No. mine is UIViewController – kaneyip May 27 '16 at 16:39
  • do u have any suggestion how to have fix navigation bar 44px both portrait & landscape. From the both snapshot the navigation bar has same height but the navigation button not align middle when in landscape. It appear align much bottom. – kaneyip May 27 '16 at 17:50
  • It depend only by constraints. Probably you must review all the navigation elements constraint: reset all, fix manual the nav bar height and do the rest in automatic constraint setting. – Alessandro Ornano May 27 '16 at 17:53