Skip to content

Instantly share code, notes, and snippets.

@thomassnielsen
Created November 2, 2014 12:48
Show Gist options
  • Save thomassnielsen/6faa57a354223d65b6bf to your computer and use it in GitHub Desktop.
Save thomassnielsen/6faa57a354223d65b6bf to your computer and use it in GitHub Desktop.
Loadingbar component for WKWebView
import UIKit
import WebKit
import LoadingBarKit
class ViewController: UIViewController {
@IBOutlet var loadingBar: LoadingBar!
var webView: WKWebView?
override func viewDidLoad() {
super.viewDidLoad()
self.webView?.addObserver(self, forKeyPath: "estimatedProgress", options: NSKeyValueObservingOptions.New, context: nil)
}
}
deinit {
self.webView?.removeObserver(self, forKeyPath: "estimatedProgress")
}
// MARK: - Progress monitoring (KVO)
override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
if (keyPath == "estimatedProgress" && object as NSObject == self.webView!) {
self.loadingBar.progress = Float(self.webView!.estimatedProgress)
}
}
}
//
// LoadingBar.swift
//
import UIKit
@IBDesignable
public class LoadingBar: UIView {
@IBInspectable public var progress: Float = 0.0 {
didSet {
UIView.animateWithDuration(0.1, animations: { () -> Void in
var width = self.frame.size.width * CGFloat(self.progress)
self.innerBar?.frame = CGRect(x: CGFloat(0.0), y: CGFloat(0.0), width: width, height: self.frame.size.height)
if self.progress >= 1.0 {
self.alpha = 0.0
} else {
self.alpha = 1.0
}
})
}
}
@IBInspectable var color: UIColor? {
didSet {
self.innerBar?.backgroundColor = self.color!
}
}
var innerBar: UIView?
override public func layoutSubviews() {
super.layoutSubviews()
self.userInteractionEnabled = false
self.backgroundColor = UIColor.clearColor()
if self.color == nil {
self.color = self.tintColor
}
if innerBar == nil {
var width = self.frame.size.width * CGFloat(self.progress)
self.innerBar = UIView(frame: CGRect(x: CGFloat(0.0), y: CGFloat(0.0), width: width, height: self.frame.size.height))
self.innerBar?.backgroundColor = self.color
self.addSubview(self.innerBar!)
}
}
}
@dattakadiyala
Copy link

dattakadiyala commented Sep 3, 2016

Any idea implementing this in swift 3
self.webView?.addObserver(self, forKeyPath: "estimatedProgress", options: NSKeyValueObservingOptions.New, context: nil)

need to be
self.webView?.addObserver(self, forKeyPath: "estimatedProgress", options: NSKeyValueObservingOptions.new, context: nil)
Just the .new insted of .New

But i am not able to observe the estimatedProgress value. Let me know if you have any ideas

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment