Swift stringByEvaluatingJavaScriptFromString [英] Swift stringByEvaluatingJavaScriptFromString
问题描述
我尝试在我的WebView上使用一些新的
I try to use some javascript on my WebView with the new
stringByEvaluatingJavaScriptFromString
function
stringByEvaluatingJavaScriptFromString
function
我不熟悉语法,所以我试过
I m not quiet familiar with the syntax so i tried
func stringByEvaluatingJavaScriptFromString( "document.documentElement.style.webkitUserSelect='none'": String) -> String?
如此处所示 https://developer.apple.com/library/ios/documentation/UIKit/Reference /UIWebView_Class/index.html#//apple_ref/occ/instm/UIWebView/stringByEvaluatingJavaScriptFromString :但是我收到一个错误Expected'。'separator
as shown here https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIWebView_Class/index.html#//apple_ref/occ/instm/UIWebView/stringByEvaluatingJavaScriptFromString: but i get a error that "Expected '.' separator"
推荐答案
您尝试调用的方法原型如下:
The method you are trying to call is prototyped as the following:
func stringByEvaluatingJavaScriptFromString(_ script :String) - >字符串?
这意味着:
- 它将
String
作为单个参数 - 它返回一个可选的
字符串
(String?
)
- It takes a
String
as single parameter - It returns an optional
String
(String?
)
你需要一个 UIWebView
使用它:
let result = webView.stringByEvaluatingJavaScriptFromString("document.documentElement.style.webkitUserSelect='none'")
因为返回类型是可选 ,它需要在你可以使用它之前解开。
但要小心,它可能没有值(即它可能等于 nil
)并且解包nil值会导致运行时崩溃。
Because the return type is optional, it needs to be unwrapped before you can use it.
But be careful, it may not have a value (i.e. it may be equal to nil
) and unwrapping nil values leads to runtime crashes.
所以你需要在使用返回的字符串之前检查一下:
So you need to check for that before you can use the returned string:
if let returnedString = result {
println("the result is \(returnedString)")
}
这意味着:如果结果
不是 nil
然后打开它并将其分配给新的常量名为 returnedString
。
This means: If result
is not nil
then unwrap it and assign it to a new constant called returnedString
.
此外,你可以将它包装在一起:
Additionally, you can wrap it together with:
let script = "document.documentElement.style.webkitUserSelect='none'"
if let returnedString = webView.stringByEvaluatingJavaScriptFromString(script) {
println("the result is \(returnedString)")
}
希望这对你有意义。
这篇关于Swift stringByEvaluatingJavaScriptFromString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!