Transparent Background with a Modal UIViewController - iphone

I have a dilema, I want to present to the user a semi-transparent view.
I found out by experimenting that if I simply pushed the transparent view to the top of my NavigationController's stack, that it would not render the transparency level I wanted. So I decided to simply add the view as a subview of the current view at the top of the stack.
This solution works, the view below is still visible, and the View is 'semi-modal'. The problem is, if the parent view inherits from UITableViewController (as mine does), then the view I 'push' onto it, does not cover the navigation bar at the top.
I really don't want to get into a situation where I am forced to enable / disable controls on the navigation bar every time I push this view, so I was wondering, if anyone knew of any solutions that I could use so that the view I push onto the UITableViewController will actually 'push over' the navigation bar?

Funny, I was just doing the same thing yesterday. Unfortunately it seems to be impossible. Once the modal view controller is in place, the previous view becomes hidden.
See this previous question on the topic.
You can still use the view controller and NIB files you have set up - here's my sample code
- (void)showUpgrade {
[self.upgradeVC viewWillAppear:NO];
[self.view addSubview:self.upgradeVC.view];
[self.upgradeVC viewDidAppear:NO];
}
- (void)hideUpgrade {
[self.upgradeVC viewWillDisappear:NO];
[self.upgradeVC.view removeFromSuperview];
[self.upgradeVC viewDidDisappear:NO];
}
- (UpgradeViewController *)upgradeVC {
if (_upgradeVC == nil) {
_upgradeVC = [[UpgradeViewController alloc] initWithNibName:[NSString stringWithFormat:#"UpgradeView_%#", self.deviceType] bundle:nil];
_upgradeVC.delegate = self;
}
return _upgradeVC;
}
You will need to store a reference to the parent view controller in the modal view controller so that you can access the -hide method. I did this through a delegate.
It would also be easy to add some animation to -show and -hide if you want it to animate up from the bottom of the screen - I was just too lazy to do this.

iOS 8 added the UIModalPresentationOverFullScreen presentation style. Set this as the presented view controller’s modalPresentationStyle. For more advanced needs, look into creating a custom presentation controller.

There is now a way to achieve this using iOS7 custom transitions :
MyController * controller = [MyController new];
[controller setTransitioningDelegate:self.transitionController];
controller.modalPresentationStyle = UIModalPresentationCustom;
[self controller animated:YES completion:nil];
To create your custom transition, you need 2 things :
A TransitionDelegate object (implementing
<UIViewControllerTransitionDelegate>)
An "AnimatedTransitioning" object
(implementing <UIViewControllerAnimatedTransitioning>)
You can find more informations on custom transitions in this tutorial : http://www.doubleencore.com/2013/09/ios-7-custom-transitions/

Try this:
ViewController *vc = [[ViewController alloc] init];
[vc setModalPresentationStyle:UIModalPresentationOverCurrentContext];
[self presentViewController:vc animated:YES completion:nil];

Have you tried looping over the Modal View Controller's subviews and setting the background color to clear for every view? This is a DFS recursive function.
- (void)setBackgroundToClearForView:(UIView *)view {
if ([view subviews]) {
for (UIView *subView in [view subviews]) {
[self setBackgroundToClearForView:subView];
}
}
if ([view respondsToSelector:#selector(setBackgroundColor:)]) {
[view performSelector:#selector(setBackgroundColor:)
withObject:[UIColor clearColor]];
}
}
To use it call:
[self setBackgroundToClearForView:self.view];
in viewDidLoad.

This will do the trick.. Try this one.
// for clear color or you can easily adjust the alpha here
YourVC *vc=[[YourVC alloc]initWithNibName:#"YourVC" bundle:nil] ;
vc.view.backgroundColor = [UIColor clearColor];
self.modalPresentationStyle = UIModalPresentationCurrentContext;
[self presentViewController:vc animated:NO completion:nil];
So that the view will be full screen unlike UIModalPresentationFormSheet..

Related

How can I create one UIViewController with two views that display one or the other depending on button clicked

I'm quite new to iOS development and I am stuck. Currently I am using one tab controller to switch between two view controllers (list and map view). This made it easier to use storyboard to configure the look of the two views.
Now the requirements have changed and the app needs to have one view controller with a segmented control that on click, displays either the list or the map view. In order to do this, I would need to make one view controller that can display list/map view.
I understand how the segmented controller part works, but I'm just stuck on how I can go about having two views with one or the other displayed in the same area.
How can I go about having two views in one view controller (if possible, utilizing storyboard)?
Thanks in advance!
You should not have two main views in a single view controller, instead you need to create one view controller per view that you want to show. However you can certainly have multiple subviews in a single view controller, which may be what works for you.
There are a number of approaches to solve this the problem, the correct approach would be to create a container UIViewController, and add as its childs the 2 viewcontrollers you want to show, them simply set the view to the view controller you want to display, but that would probably be overly complicated since you mention you are new to iOS development.
Therefore an easy solution (not sure if you can implement this in storyboard - since I don't like it), would be to have a single view controller, with the tabs, and 2 subviews of the main view, then you can simply switch between views by doing something like this:
[self.view addSubview:view1];
//to switch
[view1 removeFromSuperview];
[self.view addSubView:view2];
alternatively, you do not really need to remove it from superview but just hide it, and then use bringSubViewToFront to show the view that you need.
If you want to use the other approach I would recommend looking for this video the WWDC 2011 video titled "Implementing UIViewController Containment". This other question should be useful to: UISegmented control with 2 views
Hope that helps.
Using storyboard api you can switch between 2 viewControllers
- (void)viewDidLoad {
[super viewDidLoad];
UIViewController *viewController = [self viewControllerForSegmentIndex:self.typeSegmentedControl.selectedSegmentIndex];
[self addChildViewController:viewController];
viewController.view.frame = self.contentView.bounds;
[self.contentView addSubview:viewController.view];
self.currentViewController = viewController;
}
- (UIViewController *)viewControllerForSegmentIndex:(NSInteger)index {
UIViewController *viewController;
switch (index) {
case 0:
viewController = [self.storyboard instantiateViewControllerWithIdentifier:#"FirstViewController"];
break;
case 1:
viewController = [self.storyboard instantiateViewControllerWithIdentifier:#"SecondViewController"];
break;
}
return viewController;
}
- (IBAction)segmentChanged:(UISegmentedControl *)sender {
UIViewController *viewController = [self viewControllerForSegmentIndex:sender.selectedSegmentIndex];
[self addChildViewController:viewController];
[self transitionFromViewController:self.currentViewController toViewController:viewController duration:0.0 options:UIViewAnimationOptionTransitionNone animations:^{
[self.currentViewController.view removeFromSuperview];
viewController.view.frame = self.contentView.bounds;
[self.contentView addSubview:viewController.view];
} completion:^(BOOL finished) {
[viewController didMoveToParentViewController:self];
[self.currentViewController removeFromParentViewController];
self.currentViewController = viewController ;
}];
self.navigationItem.title = viewController.title;
}
This is in reference to iOS tutorial by Raywenderlich. Hope this helps
With Storyboard it is possible in this way.
Create UIViewController with UISegmentControl and UITableView+UITableViewCell added to it.
Now you want to add MKMapView as well, hoverer, if you simply try to place the MapView on the ViewController, it will be added as new TableView cell, which is not what we want.
That's why you should not do it so. Instead, MapView has to be added to Storyboard's List of ViewControllers
Adjust the size and origin of MapView to be the same as TableView ones.
Now, setHidden to YES for either TableView of MapView, create and synthesize outlets for them. Then in Segment control Value Changed method implement switching:
- (IBAction)switchView:(id)sender {
self.theTableView.hidden = !self.theTableView.hidden;
self.theMapView.hidden = !self.theMapView.hidden;
if (!self.theTableView.hidden) {
[self.theTableView reloadData];
}
}

iPhone -- structuring code to avoid a race condition

I have an iPhone app that uses a UINavigationController, some table views, and iAd. At the top level, my navigation controller shows the navigation bar. At lower levels, it does not.
The problem I am having is that sometimes the frame of my top level UITableView goes below the bottom of the screen. The reason it happens is this:
my viewWillAppear method looks like this:
-(void) viewWillAppear:(BOOL)animated {
[self.navigationController setNavigationBarHidden:NO animated: animated]; // changing the last animated to NO does not help.
[super viewWillAppear:animated];
}
and my viewDidLoad method looks like this:
- (void)viewDidLoad {
[self.navigationController setNavigationBarHidden:NO animated: NO];
[super viewDidLoad];
[self createTableView];
ADBannerView *abv = [[ADBannerView alloc]initWithFrame: [self initialBannerViewFrame]];
abv.delegate=self;
[self.view addSubview:abv];
self.bannerView = abv;
[self moveBannerViewOffscreen];
[abv release];
}
Lastly, moveBannerViewOffscreen looks like this:
-(void) moveBannerViewOffscreen {
// moving it down and off
CGRect newBannerFrame = self.bannerView.frame;
CGFloat screenHeight = [[UIScreen mainScreen]bounds].size.height;
newBannerFrame.origin.y=screenHeight;
bannerView.frame = newBannerFrame;
CGRect newTableFrame = self.selectionTableView.frame;
newTableFrame.size.height = self.view.bounds.size.height;
self.selectionTableView.frame = newTableFrame;
}
When the view is loading, what happens is that even though I have called
[self.navigationController setNavigationBarHidden: NO animated: NO];
the the frame of my view is not immediately adjusted to account for the navigation bar. This is still true when moveBannerViewOffscreen executes. So the height of the table view is set to 480. When the navigation bar comes in, the result is that the bottom of the table view is below the screen, and the user can't select the last row.
I'm sure I could use an NSTimer to set up some kludge to fix this. But is there a clean way to organize my code so the problem doesn't come up in the first place?
Thanks
At first glance (without fully understanding your problem, I admit) I suspect that setting yourself as the navigation controller's delegate in order to take advantage of one of these methods would help with your timing:
navigationController:didShowViewController:animated:
navigationController:willShowViewController:animated:
perhaps not moving your banner until didShowViewController has been called.
(Apologies if I didn't follow your explanation.)

Modal View Controller Won't Start in Landscape Mode

I have a navigation based app that has a detail view (UIWebView) with action buttons across the bottom in a UIToolbar. I want to add 'notes' when the 'notes' button is pushed. Everything works fine when the webview is in portrait mode. I press the notes button, the modal view opens fine and works great.
The problem occurs when the webview is in landscape mode. If I press the notes button, all the code to open the modal view gets called but all I get is a white screen. One comment: If I open the modal view in portrait and then rotate the device, it rotates fine into landscape mode. It just won't open correctly in landscape mode.
I have another button that brings up the mail composer which has the identical behavior. Here is the code in my UIWebViewController:
- (IBAction)addNotes:(id)sender
{
NotesViewController *notesViewController;
// create the view controller and set it as the root view of a new navigation
// controller
notesViewController = [[NotesViewController alloc] initWithPrimaryKey:self.record.primaryKey];
UINavigationController *newNavigationController =
[[UINavigationController alloc] initWithRootViewController:notesViewController];
// present the navigation controller modally
[self presentModalViewController:newNavigationController animated:YES];
[notesViewController release];
[self.view setNeedsDisplay]; // not sure if I need this! I was trying different things...
[self.devotionText setNeedsDisplay]; // ditto...
[newNavigationController release];
}
Any ideas? I've tried all sorts of different things to no avail. I just get a white screen with no navigation bar (although there is a status bar at the top).
Modals don't always get information about rotations, and they get their info from the status bar, which doesn't always work right. Put this in your viewWillAppear to fix: [UIApplication sharedApplication].statusBarOrientation = self.interfaceOrientation And, if you want a navigation controller inside your modal, you need to create one.
Also, you don't need the setNeedsDisplay. That only effects the current views, not the modal you are presenting.
Answer is here:
https://stackoverflow.com/a/10250747/1449618
Use the window's root view controller to present:
[self.view.window.rootViewController presentViewController:masterView
animated:YES
completion:NULL];
Wow, I lost days over that issue ... but I found a solution!
I had the same problem you had: the method "presentModalViewController:animated:" only worked in portrait mode.
After a lot of trial and error, I found out that the reason was that I had several view controllers active at the same time. I implemented a navigation system which switched between different view controllers, with one parent handling the children. (I could not use UINavigationController, because I needed a different look.)
So, my root view controller had a root view object, and several child view controllers. When a child view controller was activated, its view object was added as subview to the view of the root view controller.
The "presentModalViewController" method didn't like that. However, as soon as I set the "parentViewController" property of the child view controllers, it worked!
The problem is only that "parentViewController" is a read-only property. You have to extend the UIViewController class so you can access it.
#interface UIViewController (HelperExtension)
#property (nonatomic, assign) UIViewController *parent;
#end
#implementation UIViewController (HelperExtension)
- (UIViewController *)parent
{
return self.parentViewController;
}
- (void)setParent:(UIViewController *)parent
{
[self setValue:parent forKey:#"_parentViewController"];
}
#end
So, whenever you add the view of a child view controller to your parent view controller, call the "setParent:" method after doing it. Then it will work!
Got the same issue when presenting modally a navigation controller. Be sure to have correctly implement : shouldAutorotateToInterfaceOrientation
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
BOOL shouldAutorotate = NO;
if( isControllerMangingAllOrientations )
{
shouldAutorotate = YES;
}
else
{
shouldAutorotate = (toInterfaceOrientation == UIInterfaceOrientationPortrait);
}
return shouldAutorotate;
}
I was setting the boolean in the viewDidLoad method, not a good idea. Putting it in the initWithNibName:bundle: method is the right place.
If you use presentModalViewController just for animation like me, you can use pushViewController with animation as below answer;
Showing pushviewcontroller animation look like presentModalViewController
and you can close the viewController as below;
CATransition* transition = [CATransition animation];
transition.duration = 0.3;
transition.type = kCATransitionFade;
transition.subtype = kCATransitionFromTop;
[self.navigationController.view.layer addAnimation:transition forKey:kCATransition];
[self.navigationController popViewControllerAnimated:NO];
Hope it helps..
I had the task to show a video player in landscape mode.
AVPlayerViewController *playerViewController = [AVPlayerViewController new];
//Player init code goes here....
// #define degreesToRadian(x) (M_PI * (x) / 180.0) - was defined previously in a class header
playerViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
playerViewController.view.transform = CGAffineTransformMakeRotation(degreesToRadian(90));
playerViewController.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
[self presentViewController:playerViewController animated:YES completion:nil];
You don't need a new Navigation Controller.
- (IBAction)addNotes:(id)sender {
NotesViewController *notesViewController;
// create the view controller and set it as the root view of a new navigation
// controller
notesViewController = [[NotesViewController alloc] initWithPrimaryKey:self.record.primaryKey];
[self.navigationController pushViewController: notesViewController animated: YES];
[notesViewController release];
}

UIView disappears after modalViewController is removed from superview

In my app I have a tabBarController and in it a navigationController. One of my view controllers is a TableViewController and under the navigationBar i added a uiView as a subview to the view like this:
rectangleInfo = [[UIView alloc] initWithFrame:CGRectMake(0,0,[[UIScreen mainScreen] applicationFrame].size.width,26)]; rectangleInfo.autoresizingMask = (UIViewAutoresizingFlexibleWidth); rectangleInfo.backgroundColor = [UIColor darkGrayColor]; [self.view addSubview: rectangleInfo];
when I click on a cell in the tableView I push an UIViewController like this:
[feedViewController setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
[[self navigationController] presentModalViewController:feedViewController animated:YES];
After i pop the modal view for a couple of times with it from the tableViewNavigationController disappears the rectangleInfo UIView.
I pop my modalview like this:
[[UIApplication sharedApplication] setStatusBarHidden:NO animated:YES];
[self setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
[self dismissModalViewControllerAnimated:YES];
any idea why that subview (rectangleInfo) of the tableViewController dissapears after i remove the modal view from the superview?
thank you in advance.
I'm curious as to what you are trying to do with your rectangleInfo view? By the size of it, it looks like you are trying to mimic the status bar. Why? You can just hide the status bar if you want.
Another thing you can try is to create the UIView visually in Interface Builder. Don't actually add it to your main view, but create it as a separate UIView in the XIB with the appropriate size, etc. Then create an outlet for it in Xcode and connect it. Next, add it as a subview in code when your view controller loads. See if that makes a difference. This is especially strange since you say it only disappears after popping it several times. Do you get the same problem if you push and pop the non-modal way, e.g.:
[[self navigationController] pushViewController:feedViewController animated:YES];
[[self navigationController] popViewControllerAnimated:YES];
i solved the problem by implementing correctly the viewDidLoad and viewDidUnload methods for creating and releasing my subviews.

Transparent Modal View on Navigation Controller

I'm trying to create a transparent modal View on top of my navigation controller. Does anyone know if this is possible?
A modal view will cover the view it is pushed on top of as well as the navigation bar for your navigation controller. However, if you use the -presentModalViewController:animated: approach, then once the animation finishes the view just covered will actually disappear, which makes any transparency of your modal view pointless. (You can verify this by implementing the -viewWillDisappear: and -viewDidDisappear: methods in your root view controller).
You can add the modal view directly to the view hierarchy like so:
UIView *modalView =
[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
modalView.opaque = NO;
modalView.backgroundColor =
[[UIColor blackColor] colorWithAlphaComponent:0.5f];
UILabel *label = [[[UILabel alloc] init] autorelease];
label.text = #"Modal View";
label.textColor = [UIColor whiteColor];
label.backgroundColor = [UIColor clearColor];
label.opaque = NO;
[label sizeToFit];
[label setCenter:CGPointMake(modalView.frame.size.width / 2,
modalView.frame.size.height / 2)];
[modalView addSubview:label];
[self.view addSubview:modalView];
Adding the modalView as a subview to the root view like this will not actually cover the navigation bar, but it will cover the entire view below it. I tried playing around with the origin of the frame used to init the modalView, but negative values cause it to not display. The best method that I found to cover the entire screen besides the status bar is to add the modalView as a subview of the window itself:
TransparentModalViewAppDelegate *delegate = (TransparentModalViewAppDelegate *)[UIApplication sharedApplication].delegate;
[delegate.window addSubview:modalView];
The easiest way is to use modalPresentationStyle property of navigationController (but you'll have to make animation by yourself):
self.navigationController.modalPresentationStyle = UIModalPresentationCurrentContext;
[self presentModalViewController:modalViewController animated:NO];
modalViewController.view.alpha = 0;
[UIView animateWithDuration:0.5 animations:^{
modalViewController.view.alpha = 1;
}];
I accomplish this most easily by setting up an "OverlayViewController" that sits above all other subviews of my window or root view. Set this up in your app delegate or root view controller, and make OverlayViewController a singleton so that it can be accessed from anywhere in your code or view controller hierarchy. You can then call methods to show modal views, show activity indicators, etc, whenever you need to, and they can potentially cover any tab bars or navigation controllers.
Sample code for root view controller:
- (void)viewDidLoad {
OverlayViewController *o = [OverlayViewController sharedOverlayViewController];
[self.view addSubview:o.view];
}
Sample code you might use to display your modal view:
[[OverlayViewController sharedOverlayViewController] presentModalViewController:myModalViewController animated:YES];
I haven't actually used -presentModalViewController:animated: with my OverlayViewController but I expect this would work just fine.
See also: What does your Objective-C singleton look like?
I had this same problem and in order to The solution is to add the modal view with addSubview: and animate the change in the view hierarchy with UIView’s animateWithDuration:delay:options:animations:completion:
I added a property and 2 methods to a subclass of UIViewController (FRRViewController) that includes other functionalities. I will be publishing the whole stuff on gitHub soon, but until then you can see the relevant code below. For more info, you can check my blog: How to display a transparent modal view controller.
#pragma mark - Transparent Modal View
-(void) presentTransparentModalViewController: (UIViewController *) aViewController
animated: (BOOL) isAnimated
withAlpha: (CGFloat) anAlpha{
self.transparentModalViewController = aViewController;
UIView *view = aViewController.view;
view.opaque = NO;
view.alpha = anAlpha;
[view.subviews enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
UIView *each = obj;
each.opaque = NO;
each.alpha = anAlpha;
}];
if (isAnimated) {
//Animated
CGRect mainrect = [[UIScreen mainScreen] bounds];
CGRect newRect = CGRectMake(0, mainrect.size.height, mainrect.size.width, mainrect.size.height);
[self.view addSubview:view];
view.frame = newRect;
[UIView animateWithDuration:0.8
animations:^{
view.frame = mainrect;
} completion:^(BOOL finished) {
//nop
}];
}else{
view.frame = [[UIScreen mainScreen] bounds];
[self.view addSubview:view];
}
}
-(void) dismissTransparentModalViewControllerAnimated:(BOOL) animated{
if (animated) {
CGRect mainrect = [[UIScreen mainScreen] bounds];
CGRect newRect = CGRectMake(0, mainrect.size.height, mainrect.size.width, mainrect.size.height);
[UIView animateWithDuration:0.8
animations:^{
self.transparentModalViewController.view.frame = newRect;
} completion:^(BOOL finished) {
[self.transparentModalViewController.view removeFromSuperview];
self.transparentModalViewController = nil;
}];
}
}
Here's what I did to solve the problem - Google the details but this approach worked very well for me:
Take a screenshot of the underlying view. https://devforums.apple.com/message/266836 - this leads to a ready-made method that returns a UIView for the current screen.
Hand the screenshot to the modal view (I used a property)
Present the modal view
In the modal view controller's viewDidAppear, set the image as UIImageView at index 0. Adjust the vertical position of the image by the height of the status bar.
In the modal view controller's viewWillDisappear, remove the image again
The effect is:
The view animates in as any modal view does - the semi transparent parts of the modal view glide over the existing view
As soon as the animation stops, the background is set to the screenshot - this makes it appear as if the old view is still underneath even though it isn't.
As soon as the modal view's disappear animation starts, the image is removed. The OS meanwhile shows the old navigation view so the modal view transparently glides away and out of sight as you'd expect.
I tried animating in my own overlay view but it didn't work very well. I got a crash with no indication as to what has crashed. Rather than chase this down I did the bg view & Works really well.
Code in the modal view - I think you can figure out the rest, namely setting the property modalView.bgImage...
- (void)viewDidAppear:(BOOL)animated {
// background
// Get status bar frame dimensions
CGRect statusBarRect = [[UIApplication sharedApplication] statusBarFrame];
UIImageView *imageView = [[UIImageView alloc] initWithImage:self.bgImage];
imageView.tag = 5;
imageView.center = CGPointMake(imageView.center.x, imageView.center.y - statusBarRect.size.height);
[self.view insertSubview:imageView atIndex:0];
}
- (void)viewWillDisappear:(BOOL)animated {
[[self.view viewWithTag:5] removeFromSuperview];
}
self.modalPresentationStyle = UIModalPresentationCurrentContext;
[self presentModalViewController:newview animated:YES];
and make sure you setup the modal view background to be transparent,
self.view.background = .... alpha:0.x;
if you set modalPresentationStyle for the modal view controller to:
viewController.modalPresentationStyle = 17;
The view in the background is not removed. (TWTweetComposeViewController use it).
I did not try to pass App Store review with this code though
This post about displaying a semi-transparent "Loading..." view might give a few pointers on how to proceed.
Yeah, you have to add the view manually, and if you want to slide in from the bottom or whatever you have to do the animation yourself too.
I wrote a class to do this, and a semi-modal datepicker using that class as an example.
You can find documentation in this blog post, the code is on github
I've been researching this same issue for the past week. I tried all the various answers and examples found in Google and here on StackOverflow. None of them worked that well.
Being new to iOS programming, I wasn't aware of something called UIActionSheet. So if you're trying to accomplish this in order to show a modal overlay of buttons (such as a modal asking someone how they want to share something), just use UIActionSheet.
Here is a webpage that shows an example of how to do this.
I got this idea from https://gist.github.com/1279713
Prepare:
In the modal view xib (or scene using storyboard), I setup the full-screen background UIImageView (hook it with the .h file and give it a property "backgroundImageView") with 0.3 alpha. And I set the view (UIView) background color as plain black.
Idea:
Then in "viewDidLoad" of the modal view controller I capture the screenshot from the original status and set that image to the background UIImageView. Set the initial Y point to -480 and let it slide to Y point 0 using 0.4-second duration with EaseInOut animation option. When we dismiss the view controller, just do the reverse thing.
Code for the Modal View Controller Class
.h file:
#property (weak, nonatomic) IBOutlet UIImageView *backgroundImageView;
- (void) backgroundInitialize;
- (void) backgroundAnimateIn;
- (void) backgroundAnimateOut;
.m file:
- (void) backgroundInitialize{
UIGraphicsBeginImageContextWithOptions(((UIViewController *)delegate).view.window.frame.size, YES, 0.0);
[((UIViewController *)delegate).view.window.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage * screenshot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
backgroundImageView.image=screenshot;
}
- (void) backgroundAnimateIn{
CGRect backgroundImageViewRect = backgroundImageView.frame;
CGRect backgroundImageViewRectTemp = backgroundImageViewRect;
backgroundImageViewRectTemp.origin.y=-480;
backgroundImageView.frame=backgroundImageViewRectTemp;
[UIView animateWithDuration:0.4 delay:0.0 options:UIViewAnimationCurveEaseInOut animations:^{
backgroundImageView.frame=backgroundImageViewRect;
} completion:^(BOOL finished) {
}];
}
- (void) backgroundAnimateOut{
CGRect backgroundImageViewRect = backgroundImageView.frame;
backgroundImageViewRect.origin.y-=480;
[UIView animateWithDuration:0.4 delay:0.0 options:UIViewAnimationCurveEaseInOut animations:^{
backgroundImageView.frame=backgroundImageViewRect;
} completion:^(BOOL finished) {
}];
}
In viewDidLoad, simply call:
[self backgroundInitialize];
[self backgroundAnimateIn];
In anywhere we dismiss the modal view controller, we call:
[self backgroundAnimateOut];
Please note that this will ALWAYS animate the background image. So if this modal view controller transition style (or the segue transition style) is not set to "Cover Vertical", you may not need to call the animation methods.
I finally accomplished this, for a navigation or tab bar interface, by combining an overlay view controller (see: pix0r's answer) that's hidden / un-hidden before hiding or showing a view controller based on this very good blog post.
Concerning the view controller, the tip is to make its background view the clearColor, then the semi-transparent overlay view is visible and whatever views are added as subviews in the view controller are in front and most importantly opaque.
I've created open soruce library MZFormSheetController to present modal form sheet on additional UIWindow. You can use it to present transparency modal view controller, even adjust the size of the presented view controller.
For iOS 8+ you can use UIModalPresentationOverCurrentContext presentation style for presented view controller to easy achieve desired behavior.
UIViewController *viewController = [[UIViewController alloc] init];
viewController.view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.9f];
viewController.modalPresentationStyle = UIModalPresentationOverCurrentContext;
[self presentViewController:viewController animated:YES completion:nil];
If you also need to support iOS 7 - check this thread.
You can achieve transparent/semi-transparent modal view effect by overlaying a transparent/semi-transparent button on both the view and the navigation bar.
You can access the navigation bar through the navigationBar property of the UINavigationController.
I found that UIButton unlike UILabel will trap mouse events - hence giving the correct modal behavior.
I just found a workaround for that. Just create a 1X1 of UIViewController and add it to your parent view controller. And show the transparent modal view controller in that UIViewController.
on viewDidLoad;
self.dummyViewController = [[UIViewController alloc] init];
[self.dummyViewController.view setFrame:CGRectMake(0, 0, 1, 1)];
[self.view addSubView:self.dummyViewController.view];
when you need to open a transparentViewController;
[self.dummyViewController presentModalViewController:yourTransparentModalViewController animated:true];
If you need a screen like the attached one, the below code may help you.
The code:
MyViewController * myViewController = [[MyViewController alloc] initWithNibName:nibName bundle:nil];
UINavigationController * myNavigationController = [[UINavigationController alloc] initWithRootViewController: myViewController];
myNavigationController.modalPresentationStyle = UIModalPresentationPageSheet;
[self presentModalViewController: myNavigationController animated:YES];
If say you want a screen overlay, use the parentViewController.view, it will place above navigation bar ++
MyCustomViewController* myOverlayView = [[MyCustomViewController alloc] init];
[self.parentViewController.view addSubview:myOverlayView];
This worked for me:
UIViewController *modalViewController = [[UIViewController alloc] init];
modalViewController.view.backgroundColor = [UIColor whiteColor] colorWithAlpha:0.5];
[self showDetailViewController:modalViewController sender:nil];