iPhone自定义UINavigationBar按钮 [英] iPhone custom UINavigationBar buttons

查看:54
本文介绍了iPhone自定义UINavigationBar按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有4个标签的应用程序.每个选项卡都是一个UINavigationController.这4个UINavigationBar选项卡应该看起来相同,具有自定义背景图片,自定义backButton和自定义触发功能的右键.

I have an application with 4 tabs. Each tab is a UINavigationController. The 4 UINavigationBar tabs should look the same, have a custom background image, a custom backButton and a custom right button triggering a function.

我只想在代码中进行一次自定义,而不是在每个RootViewController中进行.

I would like to do those customizations only once in my code and not in each RootViewController.

通过将以下代码插入到我的appDelegate中,我设法获得了自定义背景图片:

I managed to have a custom background image by inserting this code into my appDelegate:

    @implementation UINavigationBar (CustomImage)
- (void)drawRect:(CGRect)rect {
    UIImage *image = [UIImage imageNamed: @"MyNavigationBar.png"];
    [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}
@end

但是我没有设法自定义后退和右键,也没有为右键指定操作.

But I didn't manage to customize the back and right buttons or specify the action for the right button.

在appDelegate中,有没有办法像背景图片一样做到这一点?
还是应该在每个RootViewController中进行自定义?

Is there a way to do that in the appDelegate, just like for the background image?
Or should I do the customization in each RootViewController?

推荐答案

viewWillAppear方法中编写以下代码

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];  
UIImage *butImage = [[UIImage imageNamed:@"back.png"] stretchableImageWithLeftCapWidth:10 topCapHeight:10];  
[button setBackgroundImage:butImage forState:UIControlStateNormal];  
[button addTarget:self action:@selector(gotoBack:) forControlEvents:UIControlEventTouchUpInside];  
button.frame = CGRectMake(0, 0, 48, 30);  
UIBarButtonItem *backButton = [[[UIBarButtonItem alloc] initWithCustomView:button] autorelease];  
self.navigationItem.leftBarButtonItem = backButton;

并为backButton编写action事件.

and write the action event for backButton.

-(IBAction)gotoBack:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

这篇关于iPhone自定义UINavigationBar按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆