gpt4 book ai didi

iphone - 普遍设置没有标题的自定义后退栏按钮

转载 作者:可可西里 更新时间:2023-11-01 04:21:22 24 4
gpt4 key购买 nike

我想为应用程序中的所有 Controller 设置自定义后退栏按钮。我试过使用这个:

[[UIBarButtonItem 外观]
setBackButtonBackgroundImage:backButtonImage
forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];

它设置图像。没关系。但是,我真正想做的是,我只想要一个不包含任何标题等的后退栏按钮的自定义按钮。上面的代码有效,但它添加了自动标题并调整后退栏按钮项目的大小。我需要为应用程序中的所有 Controller 提供固定框架、无标题后退栏按钮项。

最佳答案

我已经解决了。只需在 UIViewController 上创建一个类别并将其导入 prefix.pch 文件即可。然后写一个方法:customViewWillAppear: 并用 viewWillAppear 方法 swizzle 一下:

+(void)load{

Method viewWillAppear = class_getInstanceMethod(self, @selector(customViewWillAppear:));

Method customViewWillAppear = class_getInstanceMethod(self, @selector(viewWillAppear:));
method_exchangeImplementations(viewWillAppear, customViewWillAppear);

将上述方法添加到该类别类中。然后像这样实现您的 customViewWillAppear 方法:

-(void)customViewWillAppear:(BOOL)animated{
[self customViewWillAppear:animated];
if([self.navigationController.viewControllers indexOfObject:self] != 0 && !self.navigationItem.hidesBackButton){
UIBarButtonItem *cancelBarButton = nil;
UIButton* cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
[cancelButton addTarget:self action:@selector(popViewControllerWithAnimation) forControlEvents:UIControlEventTouchUpInside];
[cancelButton setBackgroundImage:[UIImage imageNamed:@"yourImage.png"] forState:UIControlStateNormal];
[cancelButton sizeButtonToFit];

cancelBarButton = [[UIBarButtonItem alloc] initWithCustomView:cancelButton];

NSMutableArray * leftButtons = [NSMutableArray arrayWithObject:cancelBarButton];
[leftButtons addObjectsFromArray:self.navigationItem.leftBarButtonItems];
[self.navigationItem setLeftBarButtonItem:nil];
[self.navigationItem setLeftBarButtonItems:leftButtons];
}

[self.navigationItem setHidesBackButton:YES];
}
-(void)popViewControllerWithAnimation{
[self.navigationController popViewControllerAnimated:YES];
}

现在,对于代码中的每个 Controller ,您都有一个自定义后退按钮。这花了我很多时间来实现和弄清楚。希望对大家也有帮助。

编辑:请使用以下代码支持iOS7>回扫功能;

UIImage *image = [UIImage imageForName:@"some_image"];
navBar.backIndicatorImage = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
navBar.backIndicatorTransitionMaskImage = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

创建一个基础 View Controller 并添加以下代码;

- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
}

关于iphone - 普遍设置没有标题的自定义后退栏按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18099073/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com