1
Swift에서 WKWebView를 가져 와서로드 된 웹 페이지에서 일부 자바 스크립트를 실행하는 데 문제가 발생했습니다. 사용자가 왼쪽으로 스 와이프하거나 오른쪽으로 스 와이프하거나 버튼을 클릭하면 자바 스크립트를 사용하여 웹 사이트의 배경색을 변경하려고합니다. 어떤 도움이라도 대단히 감사합니다.Swift WKWebView 및 Javascript 상호 작용
import UIKit
import WebKit
class myViewController: UIViewController, WKNavigationDelegate {
@IBOutlet var container: UIView!
var webView: WKWebView?
override func viewDidLoad() {
super.viewDidLoad()
self.webView = WKWebView()
container.addSubview(webView!)
webView?.allowsBackForwardNavigationGestures = true
webView?.navigationDelegate = self
let leftSwipe = UISwipeGestureRecognizer(target: self, action: #selector(myViewController.handleSwipes(_:)))
let rightSwipe = UISwipeGestureRecognizer(target: self, action: #selector(myViewController.handleSwipes(_:)))
leftSwipe.direction = .Left
rightSwipe.direction = .Right
view.addGestureRecognizer(leftSwipe)
view.addGestureRecognizer(rightSwipe)
}
override func viewDidAppear(animated: Bool) {
let frame = CGRectMake(0, 0, container.bounds.width, container.bounds.height)
webView!.frame = frame
let url = NSURL(string: "https://www.google.com")
let request = NSURLRequest(URL: url!)
self.webView!.loadRequest(request)
}
@IBAction func buttonClick(sender: AnyObject) {
webView?.evaluateJavaScript("document.getElementByID('hplogo').style.backgroundColor='red';", completionHandler: nil)
}
func handleSwipes(sender:UISwipeGestureRecognizer){
if (sender.direction == .Left){
webView?.evaluateJavaScript("document.getElementByID('hplogo').style.backgroundColor='black';", completionHandler: nil)
}
if (sender.direction == .Right){
webView?.evaluateJavaScript("document.getElementByID('hplogo').style.backgroundColor='green';", completionHandler: nil)
}
}
func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
webView?.evaluateJavaScript("document.getElementByID('hplogo').style.backgroundColor='red';", completionHandler: nil)
}
}
당신은 시도 할 수 있습니다이 http://www.joshuakehn.com/2014/10/29/using-javascript-with-wkwebview-in-ios-8.html – Proton
그래, 내가 Objective-C를 너무 잘 이해하지 않는다는 것을 제외하고는 튜토리얼을 보았다. @DungProton – kelsheikh
"문제가 있음"은 너무 일반적입니다. 너를 위해 일하지 않는게 뭐야? 색상이 변경되지 않았거나 잘못된 색상으로 변경 되었습니까? –