这是我的代码不建议删除IBAction我是一个初学者制作浏览器。我也这个程序很新:
import Cocoa
import WebKit
class ViewController: NSViewController, WKNavigationDelegate {
@IBOutlet weak var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
webView.navigationDelegate = self
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
}
}
@IBAction func didEnterKeyTapped( sender: NSTextField){
let urlString = sender.stringValue
guard let url = URL(string: urlString) else {return}
let urlRequest = URLRequest(url: url)
webView.load(urlRequest)
@IBAction func didnavigationButtonTapped ( sender: NSSegmentedControl){
if sender.selectedSegment == 0 {
webView.goBack()
}else {
webView.Forward()
}
}
func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
let currentUrl = webView.url?.absoluteString ?? ""
guard let windowController = view.window?.windowController as? WindowController else {return}
let textField = windowController.urlTextField
textField?.stringValue = currentUrl
}
}
}
您在ViewController
类之外声明了@IBActions。IBAction必须是类的成员。将IBActions移到类中以修复编译器错误。
你的代码中的另一个问题是你在didEnterKeyTapped
IBAction中声明了didNavigationButtonTapped
IBAction。这两个ibaction应该是独立的函数,例如:
@IBAction func didEnterKeyTapped( sender: NSTextField){
let urlString = sender.stringValue
guard let url = URL(string: urlString) else {return}
let urlRequest = URLRequest(url: url)
webView.load(urlRequest)
}
@IBAction func didnavigationButtonTapped ( sender: NSSegmentedControl) {
if sender.selectedSegment == 0 {
webView.goBack()
}else {
webView.Forward()
}
}