我正在尝试自定义进度条(NSProgressIndicator)以将彩色色调加载为渐变。例如:
预计进度值&相应的颜色
0.0 = NSColor.blue
0.5 = NSColor.red
1.0 = NSColor.green
如果你仍然不确定我想要完成什么,它看起来像这样:
我很有可能没有朝着正确的方向前进,但我想我会尝试。对macOS进行编程还是新手(尚未在学校覆盖它)。
ViewController.swift
import Cocoa
import WebKit
class ViewController: NSViewController, WKUIDelegate, WKNavigationDelegate {
// Main View Elements
@IBOutlet var webView: WKWebView!
@IBOutlet var progressBar: NSProgressIndicator!
override func viewWillAppear() {
webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
let gradient = CAGradientLayer()
gradient.colors = [NSColor.blue.cgColor,
NSColor.red.cgColor,
NSColor.green.cgColor]
gradient.locations = [0, 0.5, 1.0]
gradient.frame = view.frame
// view.layer.mask = gradient
progressBar.layer?.mask = gradient
progressBar.layer?.compositingFilter = gradient
progressBar.layer?.borderColor = CGColor.clear
progressBar.layer?.backgroundColor = CGColor.clear
progressBar.wantsLayer = true
progressBar.isBezeled = false
}
override func viewWillDisappear() {
webView.removeObserver(self, forKeyPath: "estimatedProgress")
}
// Observer for WebView Loading Progress
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if (keyPath == "estimatedProgress") {
DispatchQueue.main.async {
self.setProgress(self.webView.estimatedProgress * 100)
}
}
}
// Set Progress for ProgressBar
fileprivate func setProgress(_ value: Double) {
if value == 100 {
self.progressBar.isHidden = true
return
}
self.progressBar.isHidden = false
self.progressBar.doubleValue = value
}
override func viewDidLoad() {
super.viewDidLoad()
webView.navigationDelegate = self
let request = URL(string: "https://google.com")!
webView.load(URLRequest(url: request))
}
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
self.setProgress(0)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
self.setProgress(100)
}
}
此外,如果可能的话,你能解释为什么你的方法有效,以及为什么我的方法无法工作。我真的想提高自己的编程知识和技能。
感谢您阅读!