Swift - UINavigationBar only sometimes included in

2019-09-13 21:31发布

问题:

So I'm experiencing a bit of an odd (in my opinion) issue. I have a standard UINavigationController with a root UIViewController.

I'm adding a UITableView programatically to the view controller. When I set the frame of the table view, I set it as:

tableView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)

When I run the simulator, sometimes the tableview is positioned perfectly - sitting just under the navigation bar. However, sometimes (seemingly at random) the tableview is positioned at the top of the screen, beneath the navigation bar.

I've tried to change the Y coordinate of the tableview to be

(self.navigationController?.navigationBar.frame.height)!

But now the reverse happens: sometimes the tableview is positioned correctly, but sometimes a navigation bar sized gap appears under the navigation bar, above the tableview.

I'm pretty lost as to what's happening - perhaps it's something to do with when the navigation bar is created?

Thanks in advance.

回答1:

Try the following code...tested in Xcode 8 it worked....You mentioned about a gap appears under the navBar.Because, you didn't put the statusBar height in your code.

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

    yourTableView.frame = CGRect(x: 0, y: -(UINavigationController().navigationBar.frame.height + UIApplication.shared.statusBarFrame.size.height), width: view.frame.width, height: view.frame.height + (UINavigationController().navigationBar.frame.height + UIApplication.shared.statusBarFrame.size.height))

    print((UINavigationController().navigationBar.frame.height)) // 44.0
    print(UIApplication.shared.statusBarFrame.size.height)  // 20.0

    //You can include this code in viewDidAppears.if your view has a transition...
}

Above code will position your tableview just below navigationBar.Hope this helps...