只能声明实例方法XCODE 错误 | Swift 5

Only instance methods can be declared @IBAction | XCODE ERROR | Swift 5

这是我的代码,不建议删除 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 class 之外声明了 @IBActions。 IBAction 必须是 class 的成员。移动 class 中的 IBAction 以修复编译器错误。

代码中的另一个问题是您在 didEnterKeyTapped IBAction 中声明了 didNavigationButtonTapped IBAction。两个IBActions应该是独立的函数,比如下面这样:

@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()
    }
}