如何在swift UIWebView中重新加载gif

时间:2015-10-14 04:52:39

标签: swift uiwebview

/ *我试图在swift中重新加载UIwebView中的gif,但我不知道如何在连续循环中重新加载gif。加载请求不起作用,甚至不是reload() * /

filePath = NSBundle.mainBundle().pathForResource("alienImage", ofType: "gif")

    let gif = NSData(contentsOfFile: filePath!)

    let webViewBG = UIWebView(frame: self.view.frame)

    webViewBG.loadData(gif!, MIMEType: "image/gif",textEncodingName: String(), baseURL: NSURL())

    webViewBG.userInteractionEnabled = false;

    self.view.addSubview(webViewBG)

1 个答案:

答案 0 :(得分:1)

您可以使用NSTimer,如下面的代码所示:

myTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("myPerformeCode:"), userInfo: nil, repeats: true)

辅助方法将是:

func myPerformeCode(timer : NSTimer) {

    count++

    if count < totalCount {
        let filePath = NSBundle.mainBundle().pathForResource("\(count)", ofType: "gif")
        let gif = NSData(contentsOfFile: filePath!)
        self.webView.loadData(gif!, MIMEType: "image/gif",textEncodingName: String(), baseURL: NSURL())
        self.webView.userInteractionEnabled = false
    } else {
        count = 1
    }
}

完整代码:

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var webView: UIWebView!
    let totalCount = 61
    var count = 1
    var myTimer = NSTimer()
    override func viewDidLoad() {
        super.viewDidLoad()

    }

    @IBAction func start(sender: AnyObject) {

        myTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("myPerformeCode:"), userInfo: nil, repeats: true)
    }

    func myPerformeCode(timer : NSTimer) {

        print("Called")
        count++

        if count < totalCount {
            let filePath = NSBundle.mainBundle().pathForResource("\(count)", ofType: "gif")
            let gif = NSData(contentsOfFile: filePath!)
            self.webView.loadData(gif!, MIMEType: "image/gif",textEncodingName: String(), baseURL: NSURL())
            self.webView.userInteractionEnabled = false
        } else {
            count = 1
        }
    }
}

结果:

enter image description here

之后,无论何时切换视图,都可以使用myTimer.invalidate()删除计时器。