iOS - 在屏幕中心而不是视图显示进度指示器

问题描述:

我想在屏幕中央显示进度指示器,而不是视图.它应该是视图的中心,因为视图是可滚动的.大多数答案仅说明如何将其在视图中居中.我有这个代码:

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

但它显示在 iPhone 7 的顶部附近.正确的方法应该是什么?我还可以制作带有进度指示器的阻止弹出对话框.

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.

如果你想在滚动时将指示器视图保持在屏幕中心,你可以在当前最顶层的 UIWindow 上添加一个覆盖视图,然后添加你的指示器视图到叠加视图:

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

你应该在最上面的 UIViewController 的视图被附加到最上面的 UIWindow 之后做这个,例如,在 viewDidAppear 方法中.

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