我在基于导航的应用程序中的UIwebview中显示了一些文本和图像。它还包含一些指向数据来源的链接,即网站。它以完美的方式展示它。但是当用户点击后退按钮时,它会弹出上一个viewcontroller并转到它。但是,当用户点击链接时,我想要的是必须将后退按钮转换为浏览器的后退按钮,并按此操作。
任何建议/示例代码或教程吗?
答案 0 :(得分:17)
只要UIWebView
可以通过执行以下操作返回选项,您就可以使用浏览器后退按钮替换导航栏后退按钮:
- (void)updateBackButton {
if ([self.webView canGoBack]) {
if (!self.navigationItem.leftBarButtonItem) {
[self.navigationItem setHidesBackButton:YES animated:YES];
UIBarButtonItem *backItem = [[[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStylePlain target:self action:@selector(backWasClicked:)] autorelease];
[self.navigationItem setLeftBarButtonItem:backItem animated:YES];
}
}
else {
[self.navigationItem setLeftBarButtonItem:nil animated:YES];
[self.navigationItem setHidesBackButton:NO animated:YES];
}
}
- (void)webViewDidStartLoad:(UIWebView *)webView {
[self updateBackButton];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
[self updateBackButton];
}
- (void)backWasClicked:(id)sender {
if ([self.webView canGoBack]) {
[self.webView goBack];
}
}
答案 1 :(得分:2)
请参阅首先要做的是,您必须隐藏默认的后退按钮,如下所示
self.navigationItem.hidesBackButton = YES;
在此之后,您必须在导航栏上添加自定义后退按钮,如下所示:
UIButton * m_BackBtn = [UIButton buttonWithType:UIButtonTypeCustom];
m_BackBtn.frame = CGRectMake(4.0,5.0 + 0.0,100,30);
[m_BackBtn setTitle:@“Back”forState:UIControlStateNormal];
[m_BackBtn addTarget:selfaction:@selector(BackButtonAction)forControlEvents:UIControlEventTouchUpInside];
[m_BackBtn retain];
[self.navigationController.navigationBar addSubview:m_BackBtn];
* 并在BackButtonAction函数*
中 - (无效)BackButtonAction
{
[yourwebView goBack];
//根据需要做你的东西
}
答案 2 :(得分:0)
从XIB的后退按钮位置取一个UIBarbuttonItem 可以在其IBAction方法中编写以下内容假设您的UIWebview 对象是
UIWebView *web;
-(IBAction)goBack
{
[web goBack];
}
goBack是UIWebView的内置方法
答案 3 :(得分:0)
我喜欢@ cduhn的上述方法,因为它的简单性,但它有失去"<"在后退按钮上。如果你想保持"真实"后退按钮(带有'"<"图标),但更改了按钮的行为:
https://stackoverflow.com/a/19132881/132542
对于此处的Web视图历史记录案例,这是我在委托方法中使用的代码:
-(BOOL) navigationShouldPopOnBackButton {
if (webView.canGoBack) {
// Then just go back in the web view
[webView goBack];
// return NO to keep the current view controller loaded
return NO;
}
else {
// no web history, so pop the view
return YES;
}
}
答案 4 :(得分:0)
这是一个有点棘手的解决方案,可能不建议。但这样您就可以在导航栏上维护后退导航动画。
var urlRequest: NSURLRequest?
////////
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if navigationType == .LinkClicked {
//AViewController creates and pushes itself to the navigationController
let pushViewController = self.storyboard?.instantiateViewControllerWithIdentifier("AViewController") as! AViewController
pushViewController.urlRequest = request
self.navigationController?.pushViewController(pushViewController, animated: true)
return false
} else { //is initial request from push
return true
}
}