swift如何向 UITextView 添加activity指示灯?

标签: UITextView ios Swift
发布时间: 2016/5/8 21:01:40
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我有 UITextView ,获取和从服务器加载的文件。如何添加activity指示符来显示它正在加载?管理服务器是有点慢。

下面是代码 ︰

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

解决方法 1:

你不应该使用 NSData contentsOfURL 初始值设定项同步下载数据。那里是不能保证它会成功。你需要下载您的数据以异步方式使用 NSURLSession 方法 dataTaskWithURL,因为我已经对你说在你最后一个问题。关于您已经回答的新问题在这里。结合两个答案你应该能够完成你正在向。更多的信息评论在以下的代码 ︰

import UIKit

class ViewController: UIViewController {

    @IBOutlet var textview2: UITextView!

    // declare your activityIndicator
    let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.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 = UIColor.whiteColor()
        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) {
        // 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
        getRTFDataFromLink("https://dl.dropboxusercontent.com/u/87285547/test.rtf", textview2)
    }

    func getRTFDataFromLink(link: String,_ textView: UITextView) {
        // make sure your link is valid NSURL using guard
        guard let rtfURL = NSURL(string: link) else { return }
        // creata a data task for your url
        NSURLSession.sharedSession().dataTaskWithURL(rtfURL) {
            (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? NSHTTPURLResponse where httpURLResponse.statusCode == 200,
                let data = data where error == nil
                else { return }
            // you need to use dispatch async to update the UI
            dispatch_async(dispatch_get_main_queue(), { () -> Void in

                // 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 Swift2 Do Try Catch error handling
                do {
                    textView.attributedText = try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute : NSRTFTextDocumentType], documentAttributes: nil)
                    textView.editable = false
                } catch let error as NSError {
                    print(error.localizedDescription)
                }
            })
        }.resume()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
官方微信
官方QQ群
31647020