2012-04-03 57 views
1

我有一個包含html格式文本的UIWebView。在文中有些詞是鏈接。點擊時,他們應該將另一個視圖推入堆棧。我應該如何編寫html鏈接和相應的objective-c代碼來實現這個功能?如何在UIWebView中使用HTML鏈接將視圖推送到堆棧?

+0

http://www.theappcodeblog.com/2011/02/26/uiwebview-tutorial-link-to-an-ibaction/ OR http://inchoo.net/mobile-development/iphone-開發/如何覆蓋-uiwebview-links-request-action-with-your-own-custom-method/ – 2012-04-03 18:23:06

回答

3

建立委託的UIWebView,那麼你可以處理鏈接的動作點:

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

    return YES; 
} 
+0

我嘗試了這種解決方案,但是我無法啓動shouldStartLoadWithRequest。我以編程方式創建UIWebView並將其添加到表格單元格中。在ViewController.h文件中,我設置了這樣的代理: @interface ViewController:UIViewController 我在設置中缺少什麼? – user1279526 2012-04-04 19:03:22

+0

@ user1279526,'myWebView.delegate = self;' – beryllium 2012-04-04 19:18:19

0

斯威夫特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 
    } 
} 
相關問題