我有一个Root View控制器,我需要知道将蓝色背景更改为图像或更改其颜色,还想在右侧添加图像。 例如,在下图中,我需要将文本Root View Controller的背景更改为另一个图像或更改其颜色,并在Root View Controller文本的右侧添加一个小图标。我该怎么办呢?我已经完成Change Navigation bar Background image on each navigation但仍然无法实现它。
AppDelegate.h
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
Viewcontroller.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
答案 0 :(得分:2)
尝试将这些代码中的任何一个放入ViewWillAppear/ViewDidAppear/didFinishLaunchingWithOptions
(如果是appDelegate)。
1)navigationItem.titleView = [[UIImageView alloc] initWithImage: [UIImage imageNamed:@"urtitlebar.png"]];
OR
2)
UIView *myView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];
UIImageView *image = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"urtitlebar.png"]];
[image setFrame:CGRectMake(0, 0, 44, 44)];
[myView addSubview:image];
[self.navigationController.navigationBar addSubview:myView];
OR
3)
UINavigationBar *navBar = self.navigationController.navigationBar;
UIImage *image = [UIImage imageNamed:@"urtitlebar.png"];
[navBar setBackgroundImage:image];
编辑 :(如果您使用的是旧版SDK,请说3.2.5)
创建UINavigationBar
的子视图并使用,
drawRect:(CGRect)rect
的方法
@implementation UINavigationBar (BackgroundImage)
- (void)drawRect:(CGRect)rect
{
UIImage *navBarImage;
image = [UIImage imageNamed: @"urNavigationBar.png"];
}
[navBarImage drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}
@end
答案 1 :(得分:0)
在AppDelegate.m的didFinishLaunchingWithOptions中尝试此代码,以便在导航栏上显示自定义图像。
[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"yourImageName.png"] forBarMetrics:UIBarMetricsDefault];
您还可以将自定义按钮添加为条形按钮。
// create a custom button in viewDidLoad of your ViewController in which you want to place a custom bar button
UIButton *customBackBtn =[[UIButton alloc] init];
[customBackBtn setBackgroundImage:[UIImage imageNamed:@"yourImage.png"] forState:UIControlStateNormal];
customBackBtn.frame = CGRectMake(100, 100, 52, 31);
// set this customized button as BarButton
UIBarButtonItem *backBtn =[[UIBarButtonItem alloc] initWithCustomView:customBackBtn];
[customBackBtn addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.leftBarButtonItem = backBtn;
多数民众赞成。