【问题标题】:How can I use a html link in UIWebView to push a view on to the stack?如何在 UIWebView 中使用 html 链接将视图推送到堆栈?
【发布时间】:2012-04-03 18:15:15
【问题描述】:

我有一个包含 html 格式文本的 UIWebView。在文本中,一些词是链接。单击时,它们应该将另一个视图推送到堆栈上。我应该如何编写 html 链接和相应的 Objective-c 代码来完成这项工作?

【问题讨论】:

标签: html objective-c uiwebview hyperlink viewcontroller


【解决方案1】:

为 UIWebView 设置代理,然后你可以处理点击的链接动作:

-(BOOL) webView:(UIWebView *)inWeb shouldStartLoadWithRequest:(NSURLRequest *)inRequest navigationType:(UIWebViewNavigationType)inType {
    if ( inType == UIWebViewNavigationTypeLinkClicked ) {
        [self.navigationController pushViewController:vc animated:YES];
        return NO;
    }

    return YES;
}

【讨论】:

  • 我试过这个解决方案,但我无法让 shouldStartLoadWithRequest 触发。我正在以编程方式创建 UIWebView 并将其添加到表格单元格中。在 ViewController.h 文件中,我像这样设置委托:@interface ViewController:UIViewController 我在设置中缺少什么?
  • @user1279526, myWebView.delegate = self;
【解决方案2】:

Swift 3: 完整的 UIWebView 示例,用于在单击 html 链接时将视图推送到堆栈中并打开捆绑中的另一个 html 文件,例如<a href="imprint.html">imprint</a>

class WebViewController: UIViewController {

    @IBOutlet weak var webView: UIWebView!     
    var filename:String?

    override func viewDidLoad() {
        super.viewDidLoad()

        guard filename != nil else {
            fatalError("filename not defined")
        }

        view.backgroundColor =  UIColor.white

        webView.isOpaque = false;
        webView.delegate = self
        webView.backgroundColor = UIColor.clear

        //remove file extension first
        filename = filename!.replace(".html", replacement: "")

        let localfilePath = Bundle.main.url(forResource: filename, withExtension: "html")
        let myRequest = NSURLRequest(url: localfilePath!)
        webView.loadRequest(myRequest as URLRequest)
    }

    ...
}

extension WebViewController: UIWebViewDelegate {

    func webViewDidFinishLoad(_ webView: UIWebView) {
        //set view title from html document
        let pageTitle = webView.stringByEvaluatingJavaScript(from: "document.title")
        navigationItem.title = pageTitle
    }

    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {

         if navigationType == .linkClicked,
            let urlStr = request.url?.absoluteString,
            !urlStr.contains("http://"),
            let filename = request.url?.lastPathComponent, //e.g. imprint.html
            let vc = storyboard?.instantiateViewController(withIdentifier: "WebView") as? WebViewController{

            vc.filename = filename

            self.navigationController?.pushViewController(vc, animated: true)

            return false
        }

        return true
    }
}

【讨论】:

    猜你喜欢
    • 2011-04-18
    • 2015-04-24
    • 1970-01-01
    • 2013-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多