How would I create back, forward, and refresh buttons for a UIWebView programmatically?
I currently have a webview created but I do not want to use interface builder to create the back, forward, and refresh buttons. How would I 开发者_如何学Ccreate these buttons programmatically? I know how to create regular buttons with code, but as for webView delegate buttons, I am lost and have not been able to find many resources on it.
From the UIWebView documentation:
If you allow the user to move back and forward through the webpage history, then you can use the goBack and goForward methods as actions for buttons. Use the canGoBack and canGoForward properties to disable the buttons when the user can’t move in a direction.
Setting up the buttons would then use addTarget:action:forControlEvents:
(as pointed out by Sven):
[myBackButton addTarget:myWebView
action:@selector(goBack)
forControlEvents:UIControlEventTouchDown];
If you want to get fancy and enable/disable the buttons based on the canGoBack
and canGoForward
properties, you will have to add some KVO notifications to your UIController
.
You need to set the target and action for the buttons using addTarget:action:forControlEvents:
to your web view.
To enable/disable Back or Forward button instead of using KVO
, we can use the following "hack
"
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
if ([webView canGoBack])
[backbutton setEnabled:YES];
else
[backbutton setEnabled:NO];
if ([webView canGoForward])
[fwdbutton setEnabled:YES];
else
[fwdbutton setEnabled:NO];
}
A simpler way to enable or disable buttons is:
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
[backButton setEnabled:webView.canGoBack];
[fwdButton setEnabled:webView.canGoForward];
}
精彩评论