ios 如何在 tableView 加载时显示活动指示器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29912852/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 05:48:55  来源:igfitidea点击:

How to show activity indicator while tableView loads?

iosuitableviewswiftuiactivityindicatorview

提问by Orkhan Alizade

When I switch between my tabs it loads some seconds and I want to know that my data is loading. For that I decided to add an activity indicator.

当我在选项卡之间切换时,它会加载几秒钟,我想知道我的数据正在加载。为此,我决定添加一个活动指示器。

I wrote a little function:

我写了一个小函数:

func showActivityIndicator() {
    dispatch_async(dispatch_get_main_queue()) {
        self.spinner = UIActivityIndicatorView(activityIndicatorStyle: .WhiteLarge)
        self.spinner.frame = CGRect(x: 0.0, y: 0.0, width: 80.0, height: 80.0)
        self.spinner.center = CGPoint(x:self.loadingView.bounds.size.width / 2, y:self.loadingView.bounds.size.height / 2)

        self.loadingView.addSubview(self.spinner)
        self.view.addSubview(self.loadingView)
        self.spinner.startAnimating()
    }
}

that will show my indicator. And try to use it when I tapped from my infoController to button:

这将显示我的指标。当我从 infoController 点击按钮时尝试使用它:

@IBAction func goToMainFromInfo(sender: AnyObject) {
        self.showActivityIndicator()
        self.performSegueWithIdentifier("fromMainToInfoWActivity", sender: nil)
        self.hideActivityIndicator()
    }
}

I show it before segue perform and hide after. It doesn't help me. When I did try to use sync:

我在 segue 执行之前显示它并在之后隐藏它。它对我没有帮助。当我尝试使用同步时:

@IBAction func goToMainFromInfo(sender: AnyObject) {
    dispatch_async(dispatch_get_main_queue()) {
        self.showActivityIndicator()
        self.performSegueWithIdentifier("fromMainToInfoWActivity", sender: nil)
        self.hideActivityIndicator()
    }
}

But it doesn't help too. When I press to tab it opacity becomes 0.5 and I wait while it loading. But I do not see my activity indicator.

但这也无济于事。当我按下 Tab 键时,它的不透明度变为 0.5,我在加载时等待。但是我没有看到我的活动指示器。

What is the problem?

问题是什么?

回答by Lydia

Just try this:

试试这个:

var indicator = UIActivityIndicatorView()

func activityIndicator() {
    indicator = UIActivityIndicatorView(frame: CGRectMake(0, 0, 40, 40))
    indicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
    indicator.center = self.view.center
    self.view.addSubview(indicator)    
}

And where you want to start animating

你想从哪里开始制作动画

indicator.startAnimating()
indicator.backgroundColor = UIColor.whiteColor()

For stop:

停止:

indicator.stopAnimating()
indicator.hidesWhenStopped = true

Note:Avoid the calling of start and stop at the same time. Just give some conditions.

注意:避免同时调用start和stop。给点条件就好了。

SWIFT : 4.2Just try this:

SWIFT:4.2试试这个:

var indicator = UIActivityIndicatorView()

func activityIndicator() {
    indicator = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
    indicator.style = UIActivityIndicatorView.Style.gray
    indicator.center = self.view.center
    self.view.addSubview(indicator)   
}

And where you want to start animating

你想从哪里开始制作动画

activityIndicator()
indicator.startAnimating()
indicator.backgroundColor = .white

For stop:

停止:

indicator.stopAnimating()
indicator.hidesWhenStopped = true

回答by broccoli

Swift 3.0

斯威夫特 3.0

// UIView Extension

// UIView 扩展

fileprivate var ActivityIndicatorViewAssociativeKey = "ActivityIndicatorViewAssociativeKey"
public extension UIView {
   var activityIndicatorView: UIActivityIndicatorView {
        get {
            if let activityIndicatorView = getAssociatedObject(&ActivityIndicatorViewAssociativeKey) as? UIActivityIndicatorView {
                return activityIndicatorView
            } else {
                let activityIndicatorView = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
                activityIndicatorView.activityIndicatorViewStyle = .gray
                activityIndicatorView.color = .gray
                activityIndicatorView.center = center
                activityIndicatorView.hidesWhenStopped = true
                addSubview(activityIndicatorView)

                setAssociatedObject(activityIndicatorView, associativeKey: &ActivityIndicatorViewAssociativeKey, policy: .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
                return activityIndicatorView
            }
        }

        set {
            addSubview(newValue)
            setAssociatedObject(newValue, associativeKey:&ActivityIndicatorViewAssociativeKey, policy: .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
}

// NSObject Extension

// NSObject 扩展

public extension NSObject {
    func setAssociatedObject(_ value: AnyObject?, associativeKey: UnsafeRawPointer, policy: objc_AssociationPolicy) {
        if let valueAsAnyObject = value {
            objc_setAssociatedObject(self, associativeKey, valueAsAnyObject, policy)
        }
    }

    func getAssociatedObject(_ associativeKey: UnsafeRawPointer) -> Any? {
        guard let valueAsType = objc_getAssociatedObject(self, associativeKey) else {
            return nil
        }
        return valueAsType
    }
}

start animation

开始动画

tableView.activityIndicatorView.startAnimating()

tableView.activityIndicatorView.startAnimating()

stop animation

停止动画

tableView.activityIndicatorView.stopAnimating()

tableView.activityIndicatorView.stopAnimating()

You can find more code in Magic

您可以在Magic 中找到更多代码

回答by Ragul

Swift 2+

斯威夫特 2+

    class ViewController: UITableViewController {
        weak var activityIndicatorView: UIActivityIndicatorView!

        override func viewDidLoad() {
            super.viewDidLoad()
            let activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
            tableView.backgroundView = activityIndicatorView
            self.activityIndicatorView = activityIndicatorView
            activityIndicatorView.startAnimating()

        }
        ...
    }

回答by Shanmugasundharam

This code can help you :)

此代码可以帮助您:)

   let indicator:UIActivityIndicatorView = UIActivityIndicatorView  (activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray) 
   indicator.color = UIColor .magentaColor()
   indicator.frame = CGRectMake(0.0, 0.0, 10.0, 10.0)
   indicator.center = self.view.center
   self.view.addSubview(indicator)
   indicator.bringSubviewToFront(self.view)
   indicator.startAnimating()

回答by A.J. Hernandez

SWIFT

迅速

Place this below your class:

把它放在你的班级下面:

let indicator:UIActivityIndicatorView = UIActivityIndicatorView  (activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)

Place this in your loadView():

把它放在你的 loadView() 中:

indicator.color = UIColor .magentaColor()
indicator.frame = CGRectMake(0.0, 0.0, 10.0, 10.0)
indicator.center = self.view.center
self.view.addSubview(indicator)
indicator.bringSubviewToFront(self.view)
indicator.startAnimating()

In my case, I am requesting json objects through a func request, so I placed this at the end of that function to remove the activity indicator once the data loads:

就我而言,我通过 func 请求请求 json 对象,因此我将它放在该函数的末尾以在数据加载后删除活动指示器:

self.indicator.stopAnimating()
self.indicator.hidesWhenStopped = true

回答by Ali Abbas

Another approach, In my code I added an extension for UITableView (Swift 2.3) :

另一种方法,在我的代码中,我为 UITableView (Swift 2.3) 添加了一个扩展:

extension UITableView {
    func activityIndicator(center: CGPoint = CGPointZero, loadingInProgress: Bool) {
        let tag = 12093
        if loadingInProgress {
            var indicator = UIActivityIndicatorView()
            indicator = UIActivityIndicatorView(frame: CGRectMake(0, 0, 40, 40))
            indicator.tag = tag
            indicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.WhiteLarge
            indicator.color = //Your color here
            indicator.center = center
            indicator.startAnimating()
            indicator.hidesWhenStopped = true
            self.superview?.addSubview(indicator)
        }else {
             if let indicator = self.superview?.viewWithTag(tag) as? UIActivityIndicatorView { {
                indicator.stopAnimating()
                indicator.removeFromSuperview()
            }
        }
    }
}

Note : My tableview is embedded in a UIView (superview)

注意:我的 tableview 嵌入在 UIView (superview) 中

回答by Isuru

I use two extension methods to add an UIActivityIndicatorViewas the backgroundViewof the tableview.

我使用两种扩展方法来添加一个UIActivityIndicatorView作为backgroundViewtableview 的。

extension UITableView {
    func showActivityIndicator() {
        DispatchQueue.main.async {
            let activityView = UIActivityIndicatorView(style: .medium)
            self.backgroundView = activityView
            activityView.startAnimating()
        }
    }

    func hideActivityIndicator() {
        DispatchQueue.main.async {
            self.backgroundView = nil
        }
    }
}

You can show/hide it like this.

您可以像这样显示/隐藏它。

tableView.showActivityIndicator()
tableView.hideActivityIndicator()

回答by BharathRao

Update Swift 4.2:

更新 Swift 4.2:

1.call the activityIndicator function on viewDidLoad
eg:

1.调用activityIndi​​cator函数,viewDidLoad
例如:

var indicator = UIActivityIndicatorView()
override func viewDidLoad() {
    //Initializing the Activity Indicator
    activityIndicator()
    //Starting the Activity Indicator
    indicator.startAnimating()
    //Call Your WebService or API
    callAPI()
}

Here is the Code For Adding ActivityIndicator as Subview

这是将 ActivityIndi​​cator 添加为子视图的代码

func activityIndicator() {
            indicator = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
            indicator.style = UIActivityIndicatorView.Style.whiteLarge
            indicator.color = .red
            indicator.center = self.view.center
            self.view.addSubview(indicator)
    }

2. Do UI related Operations or API Call and stop activity indicator

2.做UI相关的操作或API调用并停止活动指示器

    func callAPI() {     
        YourModelClass.fetchResult(someParams, 
        completionHandler: { (response) in 
        //Do necessary UIUpdates
        //And stop Activity Indicator
        self.indicator.stopAnimating()
        })
    }

回答by Ahmed Lotfy

 func setupSpinner(){
    spinner = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 40, height:40))
    spinner.color = UIColor(Colors.Accent)
    self.spinner.center = CGPoint(x:UIScreen.main.bounds.size.width / 2, y:UIScreen.main.bounds.size.height / 2)
    self.view.addSubview(spinner)
    spinner.hidesWhenStopped = true
}

回答by Den Jo

Using "lazy var". It's better than function

使用“懒惰的变量”。它比功能更好

fileprivate lazy var activityIndicatorView: UIActivityIndicatorView = {
    let activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .gray)
    activityIndicatorView.hidesWhenStopped = true

    // Set Center
    var center = self.view.center
    if let navigationBarFrame = self.navigationController?.navigationBar.frame {
        center.y -= (navigationBarFrame.origin.y + navigationBarFrame.size.height)
    }
    activityIndicatorView.center = center

    self.view.addSubview(activityIndicatorView)
    return activityIndicatorView
}()

Just start the spinner anywhere

只需在任何地方启动微调器

like this

像这样

func requestData() {
  // Request something
  activityIndicatorView.startAnimating()
}