简体   繁体   中英

iOS - Display a progress indicator at the center of the screen rather than the view

I want to display a progress indicator at the center of the screen, NOT the view. It should be the center of the view because the view is scrollable. Most answers only tells how to center it in the view. I have this code:

            let screenBound = UIScreen.main.bounds
            let progressIndc = UIActivityIndicatorView()
            progressIndc.frame = CGRect(x: screenBound.width / 2 - 10,
                                        y: screenBound.height / 2 - 10,
                                        width: 20, height: 20)
            progressIndc.hidesWhenStopped = true
            progressIndc.color = UIColor.gray
            progressIndc.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray
            // self.view is scroll view
            self.view.addSubview(progressIndc)
            progressIndc.startAnimating()

But it shown near the top in iPhone 7. What should be the right way? I can also do a blocking pop-up dialog with a progress indicator.

you can use center property of UIView

progressIndc.center  =  self.view.center

for eg

let screenBound = UIScreen.main.bounds
    let progressIndc = UIActivityIndicatorView()
    progressIndc.frame = CGRect(x: screenBound.width / 2 - 10,
                                y: screenBound.height / 2 - 10,
                                width: 20, height: 20)
    progressIndc.hidesWhenStopped = true
    progressIndc.color = UIColor.gray
    progressIndc.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray
    // self.view is scroll view
    progressIndc.center  =  self.view.center
    self.view.addSubview(progressIndc)
    progressIndc.startAnimating()

output

在此输入图像描述

if you want to keep the indicator view at the center of screen while scrolling, you can add a overlay view to the current topmost UIWindow, then add your indicator view to the overlay view:

guard let topWindow = UIApplication.shared.windows.last else {return}
let overlayView = UIView(frame: topWindow.bounds)
overlayView.backgroundColor = UIColor.clear
topWindow.addSubview(overlayView)
let hudView = UIActivityIndicatorView()
hudView.bounds = CGRect(x: 0, y: 0, width: 20, height: 20)
overlayView.addSubview(hudView)
hudView.center = overlayView.center

you should do this after the topmost UIViewController's view was attached on the top UIWindow, for example, in viewDidAppear method.

you can try this one to add you indicator on top of the screen. but it's not pretty solution -

AppDelegate.sharedInstance.window?.addSubview(progressIndc);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM