我在UIWebView顶部创建了一个按钮,我想用它来按下时刷新webview。以下代码位于我的ViewController类中:
@IBOutlet weak var webView: UIWebView!
override func shouldAutorotate() -> Bool {
return false
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.Landscape
}
override func viewDidLoad() {
super.viewDidLoad()
let webView:UIWebView = UIWebView(frame: CGRectMake(30, 20, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height))
let button = UIButton(type: .System)
webView.scalesPageToFit = true
webView.multipleTouchEnabled = true
webView.backgroundColor = UIColor.whiteColor()
webView.loadRequest(NSURLRequest(URL: NSURL(string: "http://www.example.com")!))
self.view.addSubview(webView)
button.frame = CGRectMake(20, -20, 100, 100)
button.setTitle("Refresh", forState: UIControlState.Normal)
button.addTarget(self, action: Selector(reload()), forControlEvents: UIControlEvents.TouchUpInside)
webView.insertSubview(button, aboveSubview: webView)
}
func reload() {
webView.reload()
}
我创建了reload
方法来刷新webView
,但单击按钮时没有任何反应。我还尝试在viewDidLoad中创建重载方法,看看是否解决了这个问题。可能导致这个问题的原因是什么?
答案 0 :(得分:3)
您在视图中定义了webview确实加载范围,将其取出:
let webView:UIWebView = UIWebView(frame: CGRectMake(30, 20, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height))
func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(type: .System)
webView.scalesPageToFit = true
webView.multipleTouchEnabled = true
webView.backgroundColor = UIColor.whiteColor()
webView.loadRequest(NSURLRequest(URL: NSURL(string: "http://www.example.com")!))
webView.layer.zPosition = 1
self.view.addSubview(webView)
button.frame = CGRectMake(0, 0, 100, 100)
button.setTitle("Reload Page", forState: UIControlState.Normal)
button.addTarget(self, action: Selector(reload()), forControlEvents: UIControlEvents.TouchUpInside)
webView.insertSubview(button, aboveSubview: webView)
}
func reload() {
webView.reload()
}
答案 1 :(得分:3)
action: Selector(reload())
语法错误。在Xcode 7.2及以下版本中,它应该是
action: Selector("reload")
在Xcode 7.3及以上它应该是
action: #selector(ClassName.funcName)
在Xcode 7.2中,整个事情应该是
let webView:UIWebView = UIWebView(frame: CGRectMake(30, 20, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height))
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(type: .System)
webView.scalesPageToFit = true
webView.multipleTouchEnabled = true
webView.backgroundColor = UIColor.whiteColor()
webView.loadRequest(NSURLRequest(URL: NSURL(string: "http://www.example.com")!))
self.view.addSubview(webView)
button.frame = CGRectMake(20, -20, 100, 100)
button.setTitle("Refresh", forState: UIControlState.Normal)
button.addTarget(self, action: Selector("reload"), forControlEvents: .TouchUpInside)
webView.insertSubview(button, aboveSubview: webView)
}
func reload() {
webView.reload()
}