是否可以将某些图像设置为导航栏的标题?
我认为NYTimes应用程序使用导航栏,标题看起来像图像文件(之所以看起来UINavigationBar
是因为他们使用右键搜索).
您可以使用UIImageView
该UINavigationItem.titleView
财产,是这样的:
self.navigationItem.titleView = myImageView;
我发现高度约为35px的透明.png效果很好.
- (void)awakeFromNib { //put logo image in the navigationBar UIImageView* img = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"logo.png"]]; self.navigationItem.titleView = img; [img release]; }
您可以从故事板(从Xcode 7开始)直接执行此操作:
在视图控制器的主视图外创建视图.它可以是嵌套视图,也可以只是图像
将导航项添加到视图控制器
按住Ctrl键并从导航项拖动并放在外部视图上
4.选择标题视图
我已经为UINavigationBar创建了一个自定义类别,如下所示
UINavigationBar的+ CustomImage.h
#import@interface UINavigationBar (CustomImage) - (void) setBackgroundImage:(UIImage*)image; - (void) clearBackgroundImage; - (void) removeIfImage:(id)sender; @end
UINavigationBar的+ CustomImage.m
#import "UINavigationBar+CustomImage.h" @implementation UINavigationBar (CustomImage) - (void) setBackgroundImage:(UIImage*)image { if (image == NULL) return; UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; imageView.frame = CGRectMake(110,5,100,30); [self addSubview:imageView]; [imageView release]; } - (void) clearBackgroundImage { NSArray *subviews = [self subviews]; for (int i=0; i<[subviews count]; i++) { if ([[subviews objectAtIndex:i] isMemberOfClass:[UIImageView class]]) { [[subviews objectAtIndex:i] removeFromSuperview]; } } } @end
我从我的UINavigationController调用它
[[navController navigationBar] performSelectorInBackground:@selector(setBackgroundImage:) withObject:image];
这条线对你有用,我总是用它
[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"imageNavBar.png"] forBarMetrics:UIBarMetricsDefault];
我修改了UINavigationBar + CustomImage.m以使标题对用户仍然可见.只需使用insertSubview:atIndex:而不是addSubview:
UINavigationBar的+ CustomImage.m
#import "UINavigationBar+CustomImage.h" @implementation UINavigationBar (CustomImage) - (void) setBackgroundImage:(UIImage*)image { if (image == NULL) return; UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; imageView.frame = CGRectMake(0, 0, 320, 44); [self insertSubview:imageView atIndex:0]; [imageView release]; } - (void) clearBackgroundImage { NSArray *subviews = [self subviews]; for (int i=0; i<[subviews count]; i++) { if ([[subviews objectAtIndex:i] isMemberOfClass:[UIImageView class]]) { [[subviews objectAtIndex:i] removeFromSuperview]; } } } @end
这也很有效
[self.navigationController.navigationBar.topItem setTitleView:[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"YourLogo"]]];