Swift 5 Activity 指标未显示

Swift 5 Activity Indicator not showing

我检查了其他 questions/answers,但没有一个适合我。

我有很多视图控制器在 segue 准备期间从数据库加载数据。因此,我将 activity 指标设置如下:

函数 tableView/collectionView (didSelectRow/item){ ...

self.showSpinner()
self.performSegue(...) -> prepare(for segue...)  : data gets loaded
self.removeSpinner()

}

具有

中定义的功能
import UIKit

var aView : UIView?

extension UIViewController{

    func showSpinner(){
        aView = UIView(frame: self.view.bounds)
        aView?.backgroundColor = UIColor(white: 0, alpha: 0.5)

        let ai = UIActivityIndicatorView(style: .large)
        ai.center = aView!.center
        ai.color = .red
        ai.startAnimating()
        aView?.addSubview(ai)
        self.view.addSubview(aView!)

        Timer.scheduledTimer(withTimeInterval: 20, repeats: false, block: {_ in self.removeSpinner()})
    }

    func removeSpinner(){

        aView?.removeFromSuperview()
        aView = nil
    }
}

代码已执行(我检查过),但没有微调器或背景较暗的视图的迹象。

即使在我定义

var activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView()

并放

activityIndicator.startAnimating()
performSegue...
activityIndicator.stopAnimating()

没有任何反应。视图层次结构中没有新元素(预期:带有 activity 指示符的视图或只有 activity 指示符)。 怎么了?

更新:

如果我在

中调用它
func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
        self.showSpinner()  //show indicator
        return indexPath

所有代码(willSelect、DidSelect、Segue)都被执行,然后只有 1/10 秒我才能在转换到下一个视图时看到微调器。 但是,我需要在执行 DidSelect 的进一步代码之前显示微调器

感谢来自 Accelebrate 的 Bear Cahill!这是解决方案:

The problem was it was told to show the spinner and perform the segue. It doesn't do that until the function ends. Once the function ends it does both of those so not until it's performing the segue does the spinner show. You know it's showing b/c when you go back, it's there. So you need to call show spinner and allow control to go back to the run loop (let the function finish) and THEN call perform segue to load data, etc. I'd recommend maybe using a Timer: so you'd call showSpinner, then start a timer and in the body of the timer, call the perform segue. That way the function will end, the spinner will show and then perform segue will get called. Just have the timer set for like 0.01 seconds.