公司接下来的项目需要用swift内嵌h5来实现, 以前没有做过swift项目, 现在慢慢将所学的一点一滴记录一下 一个是怕自己忘了- =, 再就是希望大家看到能帮助我哈哈哈
前几天想要直接用swift上手- =发现连初始化什么的都给忘记了, 又乖乖回去先用OC简单的做了一个webView的界面
效果如下:
接下来, 我就一点点的把OC的代码用swift编写了
import UIKit
//要导入JavaScriptCore.framework库
import JavaScriptCore
//在此签订UIWebViewDelegate协议
class ViewController: UIViewController, UIWebViewDelegate {
//输入框
var textFiled = UITextField.init()
var webView = UIWebView.init()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//初始化textfield
textFiled.frame = CGRectMake(20, 40, 260, 30)
textFiled.borderStyle = .Bezel
textFiled.clearButtonMode = .WhileEditing
textFiled.backgroundColor = UIColor.whiteColor()
self.view.addSubview(textFiled)
//开始运行btn
let btn = UIButton.init(frame: CGRectMake(290, 40, 30, 30))
btn.setTitle("GO", forState: UIControlState.Normal)
btn.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
btn.addTarget(self, action: #selector(ViewController.btnAction(_:)), forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(btn)
//后退btn
let backBtn = UIButton.init(frame: CGRectMake(btn.frame.origin.x + 40, btn.frame.origin.y, 30, 30))
backBtn.setTitle("<", forState: UIControlState.Normal)
backBtn.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
backBtn.addTarget(self, action: #selector(ViewController.backBtnAction(_:)), forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(backBtn)
//前进btn
let forwardBtn = UIButton.init(frame: CGRectMake(backBtn.frame.origin.x + 40, backBtn.frame.origin.y, 30, 30))
forwardBtn.setTitle(">", forState: UIControlState.Normal)
forwardBtn.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
forwardBtn.addTarget(self, action: #selector(ViewController.forwardBtnAction(_:)), forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(forwardBtn)
webView.frame = CGRectMake(0, 80, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height - 80)
webView.backgroundColor = UIColor.lightGrayColor()
self.view.addSubview(webView)
//设置代理(不要忘记!如果不设置就无法调用webView的代理方法)
webView.delegate = self
}
/**
* parameters就是参数,return type是返回类型
func <#name#>(<#parameters#>) -> <#return type#> {
<#function body#>
}
*/
func btnAction(btn:UIButton){
//加载textfield中的网址
let request = NSURLRequest.init(URL: NSURL.init(string: "http://" + textFiled.text!)!)
webView.loadRequest(request)
}
func backBtnAction(backBtn:UIButton) {
webView.goBack()
}
func forwardBtnAction(forwardBtn:UIButton) {
webView.goForward()
}
/**
*网页加载完成调用此方法
*/
func webViewDidFinishLoad(webView: UIWebView) {
//调用提示框方法
setAlertShow()
}
//显示提示框
func setAlertShow() {
let jsString = String(format:"alert(123)")
print(jsString)
//交互
webView.stringByEvaluatingJavaScriptFromString(jsString)
}
运行效果如下: