我试图让用户调整给定网页的文本大小。我在Xcode 6中使用Swift。 HTML文件:
<!DOCTYPE html>
<html>
<body>
<h1>My First Heading</h1>
My first paragraph.
</body>
</html>
这是我试图改变大小的快速函数:
func changeWebViewFontSize(decOrInc: Int, webView: UIWebView)
{
//1 = decreace
//2 = increace
var textFontSizeTemp = defaults.objectForKey("textFontSize") as Int
switch decOrInc
{
case 1: //when decrease
defaults.setObject(textFontSizeTemp - 1, forKey: "textFontSize")
case 2: //when increase
defaults.setObject(textFontSizeTemp + 50, forKey: "textFontSize")
default:
break
}
var jsString = "document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust=\(textFontSize)"
//var jsString = "alert('test')"
webView.stringByEvaluatingJavaScriptFromString(jsString)
}
我知道javascript正在运行,因为当我在javascript中运行alert()函数时,它工作正常。请帮我查一下我的代码有什么问题!
答案 0 :(得分:0)
我写了一个像这样的例子来调整字体大小(增加点击按钮的大小):
class webViewController: UIViewController {
@IBOutlet weak var webView: UIWebView!
@IBOutlet weak var increase: UIButton!
var defaults = ["textFontSize":12]
@IBAction func btnIncreaseTapped(sender: AnyObject) {
changeWebViewFontSize(2,webView: webView)
}
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL(string: "http://stackoverflow.com/questions/28245483/resizing-uiwebview-text/28245982?noredirect=1#comment44873831_28245982")
let urlRequest = NSURLRequest(URL: url!)
webView.loadRequest(urlRequest)
}
func changeWebViewFontSize(decOrInc: Int, webView: UIWebView)
{
//1 = decreace
//2 = increace
var textFontSizeTemp = defaults["textFontSize"]! as Int
switch decOrInc
{
case 1: //when decrease
textFontSizeTemp = textFontSizeTemp - 1
case 2: //when increase
textFontSizeTemp = textFontSizeTemp + 50
default:
break
}
defaults["textFontSize"] = textFontSizeTemp
var jsString = "document.getElementsByTagName('body')[0].style.fontSize='\(textFontSizeTemp)px'"
webView.stringByEvaluatingJavaScriptFromString(jsString)
}
}