如何向UITextView添加活动指示器?

时间:2016-01-22 04:05:17

标签: ios swift uitextview uiactivityindicatorview

我有UITextView从服务器获取并加载文件。如何添加活动指示器以显示其正在加载?托管它的服务器有点慢。

这是代码:

let url = NSURL(string: "http://www.aliectronics.com.au/thefournobletruths.rtf")
let data = NSData(contentsOfURL: url!)

do {
    let options = [NSDocumentTypeDocumentAttribute : NSRTFTextDocumentType]
    let attributedString = try NSAttributedString(data: data!, options: options, documentAttributes: nil)
    print(attributedString)
    textview2.attributedText = attributedString
    textview2.editable = false
} catch {
    NSLog("\(error)")

2 个答案:

答案 0 :(得分:3)

您不应使用URL初始化程序的数据内容来同步下载数据。无法保证它会成功。你需要使用NSURLSession方法dataTaskWithURL异步下载数据,正如我在你上一篇question已经建议过的那样。关于您的新问题,已经回答here。结合两个答案,你应该能够完成你想要的。更多信息在代码bellow ::

评论
import UIKit
class ViewController: UIViewController {
    @IBOutlet var textview2: UITextView!
    // declare your activityIndicator
    let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .white)
    // you will need a new view for your activity indicator and a label for your message
    let messageFrame = UIView()
    let strLabel = UILabel(frame: CGRect(x: 50, y: 0, width: 160, height: 50))
    func displayActivityIndicator() {
        strLabel.text = "Loading file"
        strLabel.textColor = .white
        messageFrame.layer.cornerRadius = 15
        messageFrame.backgroundColor = UIColor(white: 0, alpha: 0.7)
        activityIndicator.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
        activityIndicator.startAnimating()
        messageFrame.addSubview(activityIndicator)
        messageFrame.addSubview(strLabel)
        view.addSubview(messageFrame)
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        // set your message frame (you can also position it using textview2.frame
        messageFrame.frame = CGRect(x: view.frame.midX - 80, y: view.frame.midY - 25 , width: 160, height: 50)
        // call your activity indicator method
        displayActivityIndicator()
        // call your method to download your data asynchronously
        getRTFData(from: "http://thewalter.net/stef/software/rtfx/sample.rtf", textview2)
    }
    func getRTFData(from link: String,_ textView: UITextView) {
        // make sure your link is valid NSURL using guard
        guard let url = URL(string: link) else { return }
        // creata a data task for your url
        URLSession.shared.dataTask(with: url) {
            (data, response, error) in
            // use guard to make sure you get a valid response from the server and your data it is not nil and you got no errors otherwise return
            guard
                let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
                let data = data, error == nil
            else { return }
            // you need to use dispatch async to update the UI
            DispatchQueue.main.async {
                // stop animating the activity indicator and remove the messageFrame from the view
                self.activityIndicator.stopAnimating()
                self.messageFrame.removeFromSuperview()

                // NSAttributedString data initialiser throws an error so you need to implement Do Try Catch error handling
                do {
                    textView.attributedText = try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
                    textView.isEditable = false
                } catch {
                    print(error)
                }
            }
        }.resume()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

答案 1 :(得分:0)

以下是代码如何在SWIFT中显示简单的激活器指示器 -

  var activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)//choose from the indicator styles available by default
    activityIndicator.frame = CGRectMake(0.0, 0.0, 50.0, 50.0)//set the frame of the indicator over here.
    activityIndicator.center = view.center//where you want to place. usually we place it at the centre of our superview
    view.addSubview(activityIndicator)//adding the indicator
    activityIndicator.bringSubviewToFront(view)
    UIApplication.sharedApplication().networkActivityIndicatorVisible = true

现在,无论您想要什么,我们都会添加为

activityIndicator.startAnimating()//Here we start the animation

我们通常在加载或调用从URL加载数据之前启动动画。

删除&停止动画 -

activityIndicator.stopAnimating()
activityIndicator.removeFromSuperview()

希望这对您有用,如果您愿意,可以继续进行更多自定义。您可以参考许多博客和链接以获得更多自定义。