Ahsan
Ahsan

Reputation: 2982

Issues with changing UINavigationBar background when presenting modal view controller

I am using this method to change the backgrounds of my uiviewcontrollers. It generally works when I push a view controller.

However, if the viewcontroller is presented using

[self presentModalViewController:customViewController animated:YES];

then, this code doesnt work. Can anyone kindly suggest whats wrong ?

Code used:

To have an image in the navigation bar, you have to draw it yourself, which actually isn't that hard. Save this as UINavigationBar+CustomBackground.m (it adds a custom category to UINavigationBar):

@implementation UINavigationBar (CustomBackground)

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

@end

Upvotes: 0

Views: 698

Answers (5)

Doon
Doon

Reputation: 97

The method you is to set the navigation bar image in navigation controller.

But The new view controller you present is not using navigation method. Instead, you use Modal view Controller.

I have two solution for you:

--- 1 -----

still use Modal View Controller, just add that image on the top of new view controller.

[self.view addSubview:theImage];

---- 2 -----

use

[self.navigationController pushViewController:customViewController animated:YES];

instead of

[self presentModalViewController:customViewController animated:YES];   

In this case, you are using navigation.

I will suggest the second one.

Upvotes: 0

apalvai
apalvai

Reputation: 597

You have to create a navigation controller, set the root controller and present it.

e.g.

UIViewController *vc = [[UIViewController alloc] init];

UINavigationController *cntrol = [[UINavigationController alloc] initWithRootViewController:vc];

[self presentModalViewController:cntrol animated:YES];

Upvotes: 0

Will Ayd
Will Ayd

Reputation: 7164

not sure if this is it but have you tried

[self presentViewController:customViewController animated:YES completion:NULL]

And setting whatever modalViewStyle you deem appropriate for customViewController? According to the iOS documentation, presentModalViewController is deprecated, so you may have better luck using the above message call (especially since you only seem to be having this issue with modal view controllers)

Upvotes: 0

Sharon Nathaniel
Sharon Nathaniel

Reputation: 1467

Try this ,

UIColor *image = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"imagename.png"]];

replace image name.

Upvotes: 0

Amit Shah
Amit Shah

Reputation: 4164

If you are running on iOS 5, then drawRect: is no longer called

You will need to either use the UIAppearance or subclass UINavigationController and use that to change to you image.

A tutorial for UIAppearance can be found here

(drawRect: will still work on versions below iOS 5)

Upvotes: 2

Related Questions