Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the center of screen with Navigation Bar considerations

I am trying to center a UIActivityIndicator and reuse it throughout my app. I'm facing an issue where some of my views have to be under the navigation bar, and some aren't. This happens to give my activity indicator a lower than center presentation on views where the view is not under the navigation bar. For instance:

enter image description here

All the answers on StackOverflow seem to fall under picture #2.

I've simply made an extension of UIView to show and hide the activity indicator by adding it as a subview overlay. Checking multiple posts on StackOverflow, I didn't find anything that would duplicate this question.

My question is, in a production app, how would one successfully center this view for both of these situations utilizing only one function but still support IOS version back to 9.3

like image 689
Joshua Hart Avatar asked May 04 '18 17:05

Joshua Hart


People also ask

How do I center my navigation bar?

We can center the navbar using margin: auto property. It will create equal space to the left and right to align the navbar to the center horizontally. Additionally, add the width of the navbar.

What is the purpose of a navigation bar on a website?

A navigation bar (or navigation system) is a section of a graphical user interface intended to aid visitors in accessing information. Navigation bars are implemented in file browsers, web browsers and as a design element of some web sites.

What is top navigation bar?

The top navigation for your site is the horizontal red bar that lists sections or pages of your website. In many cases, the top navigation includes dropdown menus that display subpages of sections as well.


1 Answers

There are methods on UIView to convert points and frames between different view coordinate systems (supported on iOS 2.0+, https://developer.apple.com/documentation/uikit/uiview/1622424-convert).

extension UIView {

    func centerInContainingWindow() {
        guard let window = self.window else { return }

        let windowCenter = CGPoint(x: window.frame.midX, y: window.frame.midY)
        self.center = self.superview.convert(windowCenter, from: nil)
    }

}

A UIView specifies its coordinates relative to its superview, so centerInContainingWindow() uses UIView.convert(_:from:) to obtain the center of the window in coordinates relative to its superview.

  • Picture #1, view under navigation bar: the view fills the entire window, so the center point before and after converting will be the same.
  • Picture #2, view not under navigation bar: the view fills only part of the window, so the window center after converting will be shifted to remain in the same place on screen.
like image 73
Rein Spijkerman Avatar answered Oct 11 '22 12:10

Rein Spijkerman