当点击uiwebviewswift中的按钮时打开ViewController

Opening ViewController when click on button in UIWebView swift

本文关键字:ViewController 按钮 uiwebviewswift      更新时间:2023-09-26

我有一个应用程序,它有UIWebView和Webview包含简单的按钮

这是我的WebViewController:
import UIKit
class testViewController: UIViewController {
    internal static var testID = 0
    @IBOutlet weak var myWebView: UIWebView!
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        let url = NSURL (string: "http://mydomainname/index.html");
        let requestObj = NSURLRequest(URL: url!);
        myWebView.loadRequest(requestObj);
    }
}

webView完美地显示了我的HTML

我只需要从我的iOS项目呈现newViewController当我点击我的HTML文件中的按钮?

like that:

<button onclick="myFunction()> Submit </button>
<script>
function myFunction()
{
presentViewController('myViewControllerName');
}

</script>

在iOS中有没有办法做到呢?

你可以在js的动作中分配一个方案:

window.location = yourscheme://<scheme_content>

在swift层你可以使用回调:

func webView(webView: UIWebView!, shouldStartLoadWithRequest request: NSURLRequest!, navigationType: UIWebViewNavigationType) -> Bool {
    if (request.URL.scheme == "yourscheme") {
        // Your code
    }
    return true;
}

是的,你可以这样做:

func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        if (navigationType == UIWebViewNavigationType.FormSubmitted) {
            let VC = self.storyboard?.instantiateViewControllerWithIdentifier("myViewControllerName") as? myViewControllerName
            let navigationController = UINavigationController(rootViewController: VC!)
            self.navigationController?.presentViewController(navigationController, animated: true, completion:nil)
    
        }
        return true
    }