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:
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
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With