将自定义后退按钮替换为默认值

Posted

技术标签:

【中文标题】将自定义后退按钮替换为默认值【英文标题】:Replace custom back button with default 【发布时间】:2015-05-21 17:07:48 【问题描述】:

关于如何用自定义后退按钮替换默认后退按钮有很多问题,但我不知道如何用默认后退按钮替换自定义后退按钮。

我有一个网络视图,当 [self.webView canGoBack] == YES 时,会出现一个自定义后退按钮。但是在你一路返回之后,那个自定义的后退按钮仍然存在,而不是默认的。当 [self.webView canGoBack] == NO 时,我可以做些什么来将我的自定义后退按钮替换为默认按钮?

这是我的相关代码:

@interface MerchViewController () <UIWebViewDelegate>

@property UIWebView *webView;

@end

@implementation MerchViewController

- (instancetype)init

self = [super init];
if (self) 
    self.navigationItem.title = @"Merchandise";

return self;


- (void)viewDidLoad

[super viewDidLoad];
UIWebView *webView = [[UIWebView alloc] init];
webView.scalesPageToFit = YES;
self.view = webView;
self.webView = webView;
webView.delegate = self;
[self setURL];



- (void)updateBackButton 

if ([self.webView canGoBack]) 
    
        [self.navigationItem setHidesBackButton:YES animated:NO];
        //UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"backTickets"] style:UIBarButtonItemStylePlain target:self action:@selector(backWasClicked:)];
        UIBarButtonItem *backItem = [[UIBarButtonItem alloc] backButtonWith:@"Back" tintColor:[UIColor orangeColor] target:self andAction:@selector(backWasClicked:)];
        backItem.tintColor = [UIColor orangeColor];
        [self.navigationItem setLeftBarButtonItem:backItem animated:NO];
    


else 
    /*
 [self.navigationItem setHidesBackButton:YES animated:NO];
 //UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"backTickets"] style:UIBarButtonItemStylePlain target:self action:@selector(backWasClicked:)];
 UIBarButtonItem *backItem = [[UIBarButtonItem alloc] backButtonWith:@"Fan Zone" tintColor:[UIColor orangeColor] target:self andAction:@selector(openMenu:)];
 backItem.tintColor = [UIColor orangeColor];
 [self.navigationItem setLeftBarButtonItem:backItem animated:NO];
     */





- (void)webViewDidStartLoad:(UIWebView *)webView 
[self updateBackButton];


- (void)webViewDidFinishLoad:(UIWebView *)webView 
[self updateBackButton];
[_spinner stopAnimating];


- (void)backWasClicked:(id)sender 
if ([self.webView canGoBack]) 
    [self.webView goBack];



- (void)setURL

NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.lawlorscustom.com/omaha-lancers-hockey"]];
NSLog(@"loadRequest: %@", req);
[(UIWebView *)self.view loadRequest:req];



@end

“updateBackButton”中的“else”部分被注释掉了,因为如果我不注释掉它,当视图第一次加载时,会有两个后退按钮重叠。

【问题讨论】:

【参考方案1】:

挣扎了一阵子,答案是这样做的:

[self.navigationItem setHidesBackButton:NO animated:NO];

self.navigationItem.leftBarButtonItem = self.navigationItem.backBarButtonItem;

【讨论】:

以上是关于将自定义后退按钮替换为默认值的主要内容,如果未能解决你的问题,请参考以下文章

Android ActionBar 后退按钮默认填充

自定义导航控制器的后退按钮

使用LeftBarButtonItems ios中的自定义按钮创建默认后退按钮

为啥我必须在实现自定义左 barButtonItem 之前隐藏后退按钮项?

UIBarButtonItem 的默认后退按钮背景图像出现在我的自定义

iOS:默认后退按钮显示在自定义左侧导航按钮上