/ *我试图在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)
答案 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
}
}
}
结果:
之后,无论何时切换视图,都可以使用myTimer.invalidate()
删除计时器。