【发布时间】:2011-05-14 16:14:58
【问题描述】:
我正在制作一个允许用户返回 UINavigationBar 的 iPhone 应用程序。然而,它现在的样子是可怕的。我正在尝试用我自己的图像自定义它(减去默认的 UIBarButtonItem 背景)。我的图片包含了我的自定义背景,但您仍然可以看到左侧和右侧的部分按钮。
UIBarButtonItem *cancelButton = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back_button_normal.png"] style:UIBarButtonItemStylePlain target:self action:@selector(cancel:)] autorelease];
self.navigationItem.leftBarButtonItem = cancelButton;
有没有办法删除那个空间?是否有可能我可以使用 UIButton 以便完全自定义它?我在界面构建器中做了一些事情,我将一个 UIButton 拖到 UINavigationBar 的 rightButton 中,它工作得很好。无论如何我可以通过编程方式做到这一点吗?
谢谢!
它的外观如下:
编辑#1:
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self action:@selector(cancel:) forControlEvents:UIControlEventTouchDown];
[button setTitle:@"Show View" forState:UIControlStateNormal];
[button setBackgroundImage:[UIImage imageNamed:@"back_button_normal.png"] forState:UIControlStateNormal];
UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
[self.navigationItem setLeftBarButtonItem:barButtonItem];
以下是我为 UINavigationBar 制作背景的方法(位于我的 RootViewController 中):
@implementation UINavigationBar (UINavigationBarCustomDraw)
- (void) drawRect:(CGRect)rect {
[self setTintColor:[UIColor colorWithRed:0.85f green: 0.85f blue:0.85f alpha:1]];
if ([self.topItem.title length] > 0 && ![self.topItem.title isEqualToString:@"Back to ..."]) {
[[UIImage imageNamed:@"UINavigationBar_background.png"] drawInRect:rect];
CGRect frame = CGRectMake(0, 0, 320, 44);
UILabel *label = [[[UILabel alloc] initWithFrame:frame] autorelease];
[label setBackgroundColor:[UIColor clearColor]];
label.font = [UIFont boldSystemFontOfSize: 20.0];
label.shadowColor = [UIColor colorWithWhite:0.0 alpha:1];
label.textAlignment = UITextAlignmentCenter;
label.textColor = [UIColor whiteColor];
label.text = self.topItem.title;
self.topItem.titleView = label;
} else {
[[UIImage imageNamed:@"login_button.png"] drawInRect:rect];
self.topItem.titleView = [[[UIView alloc] init] autorelease];
}
}
@end
【问题讨论】: