문제

I have a Root View controller, I need to know about changing its blue background to an image or changing its color and also want to add an image to its right side. For example in the below image i need to change the background of text Root View Controller to another image or change its color and add a small icon on right side of the Root View Controller text. How should I go about it? I have gone through Change Navigation bar Background image on each navigation but still having trouble implementing it.

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

This is my storyboard

도움이 되었습니까?

해결책

Try putting any of these codes into ViewWillAppear/ViewDidAppear/didFinishLaunchingWithOptions(in case of 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];

EDIT:(in case you're using old version of SDK say 3.2.5)

Create the subview of UINavigationBarand override the method called -drawRect:(CGRect)rect with,

@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

다른 팁

Try This code in didFinishLaunchingWithOptions of AppDelegate.m for custom image on navigation bar.

[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"yourImageName.png"] forBarMetrics:UIBarMetricsDefault];

You can also add custom button as bar button.

 // 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;

Thats It.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top