Updating navigation bar after a change using UIAppearance - ios

I'm currently customising the navigation bar background image of my iOS app using the UIAppearance proxy. There is a button for switching between two different modes which triggers a notification. This notification will change the background to a different image using again the proxy. My problem is that this change becomes visible only when I go to a different controller and I come back to it. I'm not able to force the update of the navigation bar within the controller.
I've tried this in my MainTabBarController:
- (void) onAppChangedMode: (NSNotification*)notif {
APP_MODE mode = (APP_MODE) [[notif object] integerValue];
// change navigation bar appearance
[[UILabel appearance] setHighlightedTextColor:[UIColor redColor]];
[[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:(mode == 0 ? #"navbar.png" : #"navbar2.png")] forBarMetrics:UIBarMetricsDefault];
// trying to update
for (UIViewController* vc in self.viewControllers) {
[vc.navigationController.navigationBar setNeedsDisplay];
}
}
but nothing...it's not working. Any idea how to achieve it?
Thanks!

Just remove views from windows and add they again:
for (UIWindow *window in [UIApplication sharedApplication].windows) {
for (UIView *view in window.subviews) {
[view removeFromSuperview];
[window addSubview:view];
}
}

I just have the same problem, this code will help you:
- (IBAction)btnTouched:(id)sender {
[[UADSwitch appearance]setOnTintColor:[UIColor redColor]];
// Present a temp UIViewController
UIViewController *vc = [[UIViewController alloc]init];
[self presentViewController:vc animated:NO completion:nil];//"self" is an instance of UIViewController
[vc dismissViewControllerAnimated:NO completion:nil];
}

Try this code to change the background image for the current nav bar only:
[self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
Use the above code after changing the UIAppearance. This will force a change in the nav bar of the current controller. The nav bars for the other controllers will be handled by the change in UIAppearance.

Related

UINavigation bar bottom line appears after UISearchDisplayController

I have Navigation bar, with segmented control under it and it looks like this:
So there is no bottom line since i removed it this way:
for (UIView *view in self.navigationBar.subviews) {
for (UIView *view2 in view.subviews) {
if ([view2 isKindOfClass:[UIImageView class]]) {
[view2 removeFromSuperview];
}
}
}
But when i open Archive ViewController, that contains UISearchDisplayController, and i start searching i get normal uisearchDisplayController screen like this:
Now, when i Click cancel and go back to "Home" ViewController, bottom line appears again:
It's weird, if i just go back from Archive to Home, without opening SearchController it doesnt appear.
I tried removing bottom line in ViewDidAppear in "Home" ViewController same way as i posted above, but it's kinda late, line appears first then disappears after 1-2 seconds.
I Also tried setting navigation bar shadow image to nil and it didn't do the job.
So my question is how to remove it after appearing again, any idea where should i call method i have for removing it?
in your AppDelegate.m write this code hope that will help you.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
[[UINavigationBar appearance] setBackgroundImage:[[UIImage alloc] init] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
[[UINavigationBar appearance] setShadowImage:[UIImage new]];
return YES;
}

Navigation Bar Changes Height

When I push my UIViewController to the screen from my previous controller it animates the change. But when it finishes loading it resizes my navigation bar and the jumpy transition makes it look bad. How can I fix this? All I'm doing is hiding the navigation bar in Controller A in viewWillAppear and showing it in Controller B in viewDidLoad.
Ok solved it. In viewDidLoad of Controller B (the view controller I'm pushing) add the following:
UINavigationBar *navigationBar = self.navigationController.navigationBar;
[navigationBar setBackgroundImage:[UIImage new]
forBarPosition:UIBarPositionAny
barMetrics:UIBarMetricsDefault];
[navigationBar setShadowImage:[UIImage new]];
Then in your UIViewController's XIB make a height constraint on the navigation bar and set it to 68 (from testing the actual line seems to fall in between 68 and 69). Smooth as silk.
edit: If anyone has any better ideas please add them. I'll have to modify this solution for screen rotation so its not perfect.
You can do all in your controller A like this:
- (void)viewWillAppear:(BOOL)animated
{
[self.navigationController setNavigationBarHidden:YES animated:animated];
[super viewWillAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[self.navigationController setNavigationBarHidden:NO animated:animated];
[super viewWillDisappear:animated];
}

Create the navigation bar in viewDidLoad

I am creating my navigation bar in viewDidLoad. I saw in many sample codes that a navigation bar should be created in viewWillAppear. If my view controller is the root view controller, the navigation bar background image is not set. Else it seems to works normally. Is there any way that I can create the navigation bar completely and only once in the whole life cycle of the view controller and not in viewWillAppear?
Current Code:
- (void)viewDidLoad
{
[self initializeNavigationBar];
}
I do not want to do this in the viewWillAppear, as I present views. Closing these presented views, calls viewWillAppear. Thus, the navigation bar is reinitialized.
The following code is what I'm AVOIDING:
- (void)viewWillAppear
{
[self initializeNavigationBar];
}
Navigation Bar Creation Method:
- (void)initializeNavigationBar
{
navBar = [[ICANavBarView alloc] initWithFrame:CGRectMake(0, 0, 768, 44)];
navBar.delegate = self;
[navBar createViewWithTitle:StringForKey(#"company_short_title")];
[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:#"nav_bar_bg"] forBarMetrics:UIBarMetricsDefault];
[self.navigationItem setTitleView:navBar];
[self.navigationItem setHidesBackButton:YES];
//iOS7 Bug fixation of Navigation Bar
[navBar hideStatusBarOnViewController:self];
[self.navBar enableEditButton:(imageView.layer.sublayers.count > 0)];
}

iMessages change text color

My app is showing iMessages ViewController via UIActivityController. However, the colors of labels are all messed up (blue so they are barely visible). I think this is because the view controller is using my app's tint color. See below.
How can i fix this?
thanks!
I ran into something similar with presenting MFMailComposerViewController modally. Try setting the appearance of your app's tint color to nil when presenting the activity controller, and then back to your desired app tint when it completes. Here's what I did with MFMailComposer. You should be able to modify for your activity controller:
...
[[UINavigationBar appearance] setBarTintColor:nil]; // Set to default before presenting
MFMailComposeViewController *mailVC = [[MFMailComposeViewController alloc] init];
mailVC.mailComposeDelegate = self;
[self.navigationController presentViewController:mailVC animated:YES completion:nil];
...
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
[[UINavigationBar appearance] setBarTintColor:MyAppsCustomColor]; // set it back when finished
[self.navigationController dismissViewControllerAnimated:YES completion:nil];
}
EDIT
When I use this solution, it changes the nav bar appearance in the presented modal that is selected in the activity view controller (messages, mail, etc). I'm setting my app's nav bar appearance to blue in my delegate, and then back to blue in the completion block. The app's nav bar remains blue, and the presented messages/mail modal is shown with the default light gray nav bar.
UIActivityViewController* avc =
[[UIActivityViewController alloc] initWithActivityItems:#[#""]
applicationActivities:nil];
avc.completionHandler = ^(NSString *activityType, BOOL completed) {
// ...
dispatch_async(dispatch_get_main_queue(), ^{
// Set tint color back to blue.
// This block is executed whether the user finishes or cancels.
[[UINavigationBar appearance] setBarTintColor:[UIColor blueColor]];
[[self navigationController] setNeedsStatusBarAppearanceUpdate];
});
};
[[UINavigationBar appearance] setBarTintColor:nil];
[self presentViewController:avc animated:YES completion:nil];

UINavigationBar Appearance on Modal Not Setting

I am using the following code in my appDelegate to set the appearance of my UINavigationBar and status bar throughout my app:
[[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
[[UINavigationBar appearance] setTitleTextAttributes:#{NSForegroundColorAttributeName: [UIColor whiteColor]}];
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
This code correctly sets the appearance of everything to white everywhere except when a third-party modal viewController is prevented, such as from the Dropbox API or the Mail/Message viewController from a UIActivityViewController. I've included some screenshots to show how these are looking.
UIActivityViewController Mail:
UIActivityViewController Message:
Dropbox API:
I tried putting this in
[[UINavigationBar appearanceWhenContainedIn:[MFMailComposeViewController class], nil] setTitleTextAttributes:#{NSForegroundColorAttributeName: [UIColor whiteColor]}];
as well as
[[UINavigationBar appearanceWhenContainedIn:[UIActivityViewController class], nil] setTintColor:[UIColor whiteColor]];
and neither one is working.
Like you, I've been trying to alter the appearance of UIActivityViewController and it's "sub" controllers. It seems that in iOS7 the appearance API is somewhat buggy. UIActivityViewController is probably a different process and for sure a separate window, so I'm not really surprised that it's troublesome to style it.
Anyway I found an interesting way around this issue, but your designers might not like it. Create a subclass of UIWindow (ex: MyWindow), instantiate it as your main window and every time you use appearance API use it like this:
[UINavigationBar appearanceWhenContainedIn:[MyWindow class], nil].barTintColor = [UIColor redColor];
This way you'll only style views that actually belong to your application and the Apple-provided views will remain white/blue. I guess it's not the solution you were looking for, but on the other hand it gives users a good understanding what is your app and what is system-provided ;)
In iOS 8 the UIActivityViewController presents its individual compose controllers on the root view controller of your application.
You need to subclass your root view controller (whether it be a UIViewController or UINavigationController) and add the following code.
#interface UINavigationControllerBarColor : UINavigationController
#end
#implementation UINavigationControllerBarColor
- (void)presentViewController:(UIViewController *)viewControllerToPresent animated:(BOOL)flag completion:(void (^)(void))completion {
[super presentViewController:viewControllerToPresent animated:flag completion:^{
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
if (completion) {
completion();
}
}];
}
#end
and then instead of initializing a UINavigationController in the AppDelegate or storyboard, initialize your newly subclassed controller.
Some other recommendations subclass the UIActivityViewController but this does not work.
If you want to change the bar button and title colors as well use the following in your application:didFinishLaunching:
[[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
[[UINavigationBar appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
[UIColor whiteColor], UITextAttributeTextColor,
[UIFont systemFontOfSize:18.0f], UITextAttributeFont,
nil]];
[[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil] setTintColor:[UIColor whiteColor]];
I've been struggling with this same issue for hours and my conclusion is that all activities from the UIActivityViewController may have their own style implementation and will look depending on that.
Basic problem: You can customise something to look ok for mail and messages, but other apps may look wrong. i.e: Facebook Messanger for some reason forces status bar to be light.
My recommendation: Create a subclass of UIWindow, use that subclass within your application and target UIAppearance to that window class and let the system's interfaces to just be :), (or with minor changes like tint color).
#interface MyWindow : UIWindow
#end
// further in code
[[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:#[[MyWindow class]]] setTintColor:[UIColor orangeColor]];
FYI: We have literally no control over status bar when using UIActivityViewController
Hope this helps.
Since there is no solution until now, I did the following to set the color of navigation bar of UIActivityViewController modal to white (as my app's navigation bar color is blue) so that the users can at least see the buttons:
[[UINavigationBar appearance] setBarTintColor:[UIColor whiteColor]];
When the user is done with the UIActivityViewController modal, the app's main navigation bar color is returned to blue.
Hopefully somebody will post a better solution.
I found a solution to change the text color of the Send and Cancel buttons.
Check my answer from here.
Try this:
[[UINavigationBar appearance] setBarTintColor:[UIColor whiteColor]];
I have the same problem and I used ActivityViewController's completion handler delegate to set back my bar Tint color to white with this line :
shareViewController.completionWithItemsHandler = ^(NSString *activityType, BOOL completed, NSArray *returnedItems, NSError *activityError) {
[[UINavigationBar appearance] setTitleTextAttributes:#{NSForegroundColorAttributeName:[UIColor whiteColor]}];
};
However this doesn't work anymore on iOS 8... They changed little bit the completion handler format, the code got executed but the color didn't change.
So in order not to waste all of my time here is my quick fix :
I am still changing the global color with this line just before showing the sharing controller (with comment for maintenance)
[[UINavigationBar appearance] setTitleTextAttributes:#{NSForegroundColorAttributeName:[UIColor darkGrayColor]}]; // Note : In ViewWillAppear the color is set back to white
In each view controller that are calling a UIActivityViewController, I am setting in the viewWillAppear method the code to get the color back.
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[[UINavigationBar appearance] setTitleTextAttributes:#{NSForegroundColorAttributeName:[UIColor whiteColor]}];
}
This works good although it produce lack of cohesion in the code.
I used walapu's answer to make my own solution. The point is, that I set up navigation bar tint color also in presentViewController:animated:completion: and not using appearance proxy, but directly for MFMailComposeViewController.
- (void)presentViewController:(UIViewController *)viewControllerToPresent animated:(BOOL)animated completion:(void (^)(void))completion
{
if ([viewControllerToPresent isKindOfClass:[MFMailComposeViewController class]]) {
[((MFMailComposeViewController *)viewControllerToPresent).navigationBar setTintColor:[UIColor whiteColor]];
}
[super presentViewController:viewControllerToPresent animated:animated completion:^{
if ([viewControllerToPresent isKindOfClass:[MFMailComposeViewController class]]) {
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
}
if (completion) {
completion();
}
}];
}
I had a problem in particular with iMessage. Had to set navbar background image, setting the tint didn't work. Used slicing to stretch a 2x2 pixel image with my color.
[UINavigationBar.appearance setBackgroundImage:[UIImage imageNamed:#"red"]
forBarMetrics:UIBarMetricsDefault];
Here I change the nav bar's global appearance immediately before presenting the activity view, and change it back once the activity view is dismissed. (Tested on iOS 12, Swift 5)
let activityVC = UIActivityViewController...
// Temporarily change the nav bar button's tint color.
let originalColor = UINavigationBar.appearance().tintColor
activityVC.completionWithItemsHandler = { type, completed, items, error in
UINavigationBar.appearance().tintColor = originalColor
}
UINavigationBar.appearance().tintColor = UIColor.blue
present(activityVC, ...

Resources