【发布时间】:2016-06-27 14:53:37
【问题描述】:
我正在将网站加载到UIWebView。该网站包括一个按钮和一个文本字段。在应用程序本身中,我存储了一个字符串。现在我想将此字符串粘贴到网站的文本字段中(已在UIWebView 中加载)。有人知道我如何在 Swift 中做到这一点吗?非常感谢您的回答。
【问题讨论】:
标签: html swift string uiwebview swift2
我正在将网站加载到UIWebView。该网站包括一个按钮和一个文本字段。在应用程序本身中,我存储了一个字符串。现在我想将此字符串粘贴到网站的文本字段中(已在UIWebView 中加载)。有人知道我如何在 Swift 中做到这一点吗?非常感谢您的回答。
【问题讨论】:
标签: html swift string uiwebview swift2
您可以使用stringByEvaluatingJavaScriptFromString。
假设你的网站是这样的:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Hello world</title>
</head>
<body>
<label for="name">Name:</label>
<input type="text" name="name" value="" id="name">
</body>
</html>
您希望将名称字段中的值设置为应用中用户输入的某个值:
override func viewDidLoad() {
webView.delegate = self
}
func webViewDidFinishLoad(webView: UIWebView) {
// This is the value you want to pass into the website, it can be something that
// the user entered into your app. Here, I use a hard coded value for convenience
let name = "John Smith"
// Make sure the element's id in getElementById matches your HTML code
var js = "var textfield = document.getElementById('name');\n"
js += "textfield.value = '" + name + "';"
webView.stringByEvaluatingJavaScriptFromString(js)
}
【讨论】: