我有一个包含html格式文本的UIWebView。在文中有些词是链接。单击时,它们应该将另一个视图推送到堆栈。我应该如何编写html链接和相应的objective-c代码才能使其工作?
答案 0 :(得分: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;
}
答案 1 :(得分:0)
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
}
}