我想显示自定义导航栏后退按钮。我想只显示图像。我想在整个应用程序中使用此按钮也不想在每个文件中创建此按钮。我怎么样?
这是我的代码:
// Set the custom back button
UIImage *buttonImage = [UIImage imageNamed:@"back_arrow.png"];
//create the button and assign the image
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:buttonImage forState:UIControlStateNormal];
//set the frame of the button to the size of the image (see note below)
button.frame = CGRectMake(0, 0, buttonImage.size.width, buttonImage.size.height);
[button addTarget:self action:@selector(popViewControllerAnimated:) forControlEvents:UIControlEventTouchUpInside];
//create a UIBarButtonItem with the button as a custom view
UIBarButtonItem *customBarItem = [[UIBarButtonItem alloc] initWithCustomView:button];
self.navigationItem.leftBarButtonItem = customBarItem;
但这仅在当前页面上显示。
另一个代码:
[[UIBarButtonItem appearance] setBackButtonBackgroundImage:[UIImage imageNamed:@"back_arrow.png"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
使用此代码后退按钮图像显示在整个应用程序中。但文字“后面”也在显示。我该如何解决这个问题。
提前致谢。
答案 0 :(得分:11)
我过去曾用过一个类别来做这件事。
在UIBarButtonItem上创建一个名为+ projectButtons(或其他)的类别。
然后你可以拥有像......这样的功能。
+ (UIBarButtonItem)backArrowButtonWithTarget:(id)target action:(SEL)action
{
UIImage *buttonImage = [UIImage imageNamed:@"back_arrow.png"];
//create the button and assign the image
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:buttonImage forState:UIControlStateNormal];
//set the frame of the button to the size of the image (see note below)
button.frame = CGRectMake(0, 0, buttonImage.size.width, buttonImage.size.height);
[button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
//create a UIBarButtonItem with the button as a custom view
UIBarButtonItem *customBarItem = [[UIBarButtonItem alloc] initWithCustomView:button];
return customBarItem;
}
然后将其添加到导航栏中,如此...
self.navigationItem.leftBarButtonItem = [UIBarButtonItem backArrowButtonWithTarget:self action:@selector(popViewControllerAnimated:)];
这意味着您只需要一行代码来创建它,但您仍然可以在您使用它的每个VC中定制目标和操作。如果您决定更改按钮的外观,那么所有内容都完成了一个地方。