一、需求:
ViewController中的某一部位嵌入一小方块WebView,
比如WebView为广告图九宫格,点击某一个广告图要跳转到app中的相应某一个ViewController
二、惊喜
1、花了大半天查了很多资料,然后把思路带偏了
2、一直以为要动用javascript
3、不用和javascript交互 不用和javascript交互 不用和javascript交互
4、不用特意 不用特意 不用特意 去获得图片的链接
三、原理:总共有二个关键点
关键点一 return false :
表示网页内的点击不响应,否则会在webview里面点击前进
关键点二 return true : 原生控件响应且加载webView
所有代码在此
//
// ViewController.swift
// WebViewDemo
//
// Created by apiapia on 9/7/17.
// Copyright © 2017 WWW.ELINKNET.CN. All rights reserved.
//
import UIKit
class ViewController: UIViewController,UIWebViewDelegate{
let urlString = "https://api.xxxxyyyzzz.com/index.php?r=app/v1/site/get-home-m1"
lazy var webView:UIWebView = {
let webView = UIWebView.init()
webView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height)
let url = URL(string: self.urlString)
webView.loadRequest(URLRequest(url: url!))
webView.delegate = self
return webView
}()
override func viewDidLoad() {
super.viewDidLoad()
automaticallyAdjustsScrollViewInsets = true
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
view.addSubview(webView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
extension ViewController {
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
let nextVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "NextViewController") as! NextViewController
// nextVC.urlLabel.text = request.url?.absoluteString
if (request.url?.absoluteString.hasPrefix("https://api.xxxxyyyzzz.com/"))! {
navigationController?.pushViewController(nextVC, animated: true)
//MARK: - 关键点一: 表示网页内的点击不响应,否则会在webview里面点击前进
return false
}
//MARK: - 关键点二: 原生控件响应且加载webView
return true
}
}
就这么简单 easy!
网友评论