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

ぃ、小莉子 提交于 2021-02-10 03:26:17

问题


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.


回答1:


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 viewDidAppearmethod.




回答2:


you can use center property of UIView

progressIndc.center  =  self.view.center

for e.g

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




回答3:


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);


来源:https://stackoverflow.com/questions/43775200/ios-display-a-progress-indicator-at-the-center-of-the-screen-rather-than-the-v

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!