I am working off the base navigation template which has a master-view holding the navbar etc and finally loads a view inside it when the app is built.
I am wondering how to make it so the user can navigate several views inside this master view without adding anything to the navigation stack like you normally would when changing views inside a navigator app.
The way I plan to transition these views will be with a swipe gesture..
any help would be greatly appreciated, hopefully I have explained my problem well enough as its quite a hard thing to explain.
I'd go about this using a UIScrollView with pagination.
But in the case that doesn't work for you, try this:
- (void) swipedScreen:(id) sender {
//I'll leave getNewView to you to implement based on how you want to get the new view
UIView *newView = [self getNewView];
self.view = newView;
}
- (void) setupSwipeGestureRecognizer {
UISwipeGestureRecognizer *swipeGesture = [[[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(swipedScreen:)] autorelease];
swipeGesture.direction = (UISwipeGestureRecognizerDirectionUp|UISwipeGestureRecognizerDirectionDown);
[window addGestureRecognizer:swipeGesture];
}
- (void) viewDidLoad {
[self setupSwipeGestureRecognizer];
}
And don't forget to remove the gesture recognizer wherever you feel appropriate.
I have a UIViewController and I wish to place a simple UITabBar like the in the screenshot below: I don't want to use an UITabBarController. In fact, my original setup uses one, and it's easy as cake to get it to work.
However, the thing is I found out it's a bad idea to put UITabBarControllers inside Navigation Controllers, so I'm forced to refactor the hierarchy (so please don't suggest using one).
Given an UIViewController, how can I add an UITabBar on the bottom programatically? I got my UITabBarDelegate all setup to show a specific view when 1 of the tab bars is clicked, but the problem is when the view controller loads, no tab bar shows up! Here's my code to do that:
- (void) viewDidLoad {
...some initialization...
CGRect frame = CGRectMake(0, 431, 320, 49);
profileItem = [[UITabBarItem alloc] init];
profileItem.image = icon;
profileItem.title = #"Diet";
tabBar = [[UITabBar alloc] initWithFrame:frame];
NSArray* items = [[NSArray alloc] initWithObjects:profileItem, nil];
tabBar.items = items;
tabBar.delegate = self;
[tabBar setSelectedItem:[tabBar.items objectAtIndex:0]];
[self.view addSubview:tabBar];
[super viewDidLoad];
}
What am I missing here?
EDIT: Argh, I found out it has to do with the frame... Hmm.. what y-coordinate should I use if I have an existing navigation header on top?
You mention in your edit that you already determined that it has to do with the frame. Your problem may stem from the fact that your view's size in viewDidLoad isn't guaranteed to be the same is it will be when it eventually gets displayed. UIKit resizes the view to fit the context in which it's being displayed just before viewWillAppear:.
If you want to add the tab bar in viewDidLoad, then you should position it at the bottom of your view's frame by doing some math:
CGRect frame = CGRectMake(0, self.view.bounds.size.height - 49,
self.view.bounds.size.width, 49);
Then set an appropriate autoresizingMask so that it remains at the bottom even if UIKit resizes your view:
tabBar.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth;
Is it possible with a standard UINavigationController-rooted app, to have a single ADBannerView visible at the bottom of the screen, below the view hierarchy? That is, without modifying each view-controller/view that can be pushed to the root UINavigationController, can I have a global ADBannerView be visible?
I'm not sure how to set this up, either in IB or in code. Help?
I see similar questions with vague answers. I'm looking for a concrete example.
EDIT: The better way to do this in iOS5+ is likely to use view controller containment. That is, make a root controller that contains your ad and application controller (nav, tab, etc.).
I figured out a way to do this. Here is what I did:
For my first attempt I created a new view controller called AdBannerController. For its view I created a full-screen view and two subviews. The first subview (contentView) is for regular content, the second is the AdBannerView. I used an instance of this view controller as the view controller associated with the app window ( [window addSubview: adBannerController.view] ). Then I added my UINavigationController.view as a subview of adBannerController.view: [adBannerController.contentView addSubview: navigationController.view].
This mostly worked except that viewcontrollers pushed to the UINavigationController never got their will/did-load/unload methods called. Shucks. I read in a few places that this is a symptom of the UINavigationController view not being a direct descendant of the app window.
For my second attempt I took the same AdBannerController and derived it from UINavigationController. This time, I did the following in loadView:
- (void)loadView
{
[super loadView];
_contentView = [self.view retain];
self.view = [[[UIView alloc] initWithFrame: _contentView.frame] autorelease];
[self.view addSubview: _contentView];
_adView = [[ADBannerView alloc] initWithFrame: CGRectMake(0, _contentView.bounds.size.height, 320, 50)];
_adView.currentContentSizeIdentifier = ADBannerContentSizeIdentifier320x50;
_adView.delegate = self;
[self.view addSubview: _adView];
/* for visual debugging of view layout
[[_mainView layer] setCornerRadius: 6.0];
[[_mainView layer] setMasksToBounds: YES];
[[_mainView layer] setBorderWidth: 1.5];
[[_mainView layer] setBorderColor: [[UIColor grayColor] CGColor]];
*/
}
Notice what happens - I let the superclass UINavigationController construct its regular "content" view, but I swap it out and replace it with my own view which is a container for both the content and ad views.
This works pretty well. I'm also using three20 and there were a few things required to make this work with that setup, but not too bad.
I hope this helps someone!
In Apple's dev sample code the iAdSuite project contents projects that have this done for you. Highly recommended.
In my root view controller (w/ ADBannerViewDelegate) I setup my banner by adding it to the nav controller view, which keeps it on top at all times:
banner = [[ADBannerView alloc] init];
banner.delegate = self;
banner.frame = CGRectMake(0.0, 430.0, banner.frame.size.width, banner.frame.size.height);
[self.navigationController.view addSubview:banner];
Note you will have to comment out layoutAnimated in delegate method bannerViewDidLoadAd as it will try to move the ad view up:
- (void)bannerViewDidLoadAd:(ADBannerView *)banner
{
//[self layoutAnimated:YES];
}
I adapted the approach suggested in the iAdSuite given here
http://developer.apple.com/library/ios/#samplecode/iAdSuite/Introduction/Intro.html
I downloaded the code and focused on the 'tab' example. I copied over the BannerViewController.h/.m as is into my project.
I created all my views in the usual way with the storyboard approach. However, in my AppDelegate class I then accessed the already built tab bar - containing all the storyboard built viewControllers.
The AppDelegate class implements the TabBarControllerDelegate protocol:
#interfaceAppDelegate : UIResponder <UITabBarControllerDelegate, UIApplicationDelegate>
The AppDelegate implementation didFinishLaunchingWithOptions method grabs the pre-built tabBar, setting its delegate to self (e.g. the AppDelegate class).
-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:
// ----------------------------------------------------------
// Set the TabBarController delegate to be 'self'
// ----------------------------------------------------------
_tabBarController = (UITabBarController*)self.window.rootViewController;
// tabController.selectedIndex = [defaults integerForKey:kOptionLastTabSelectedKey];
_tabBarController.delegate = self;
// update tab bar per iAdSuite approach
[self updateiAd];
I then built a new set of controllers per the iAdSuite approach and reset the tab bar with these new tab bar items.
-(void)updateiAd {
NSArray* viewControllers = [_tabBarController viewControllers];
NSMutableArray*newViewControllers = [[NSMutableArray alloc] init];
BannerViewController*bvc=NULL;
for(UIViewController * vc in viewControllers) {
bvc = [[BannerViewController alloc] initWithContentViewController:vc];
[newViewControllers addObject:bvc];
}
// set the new view controllers, replacing the original set
[_tabBarController setViewControllers:newViewControllers];
}
This approach puts the same 'ad' at the bottom of each view, exactly as needed. I also had to set the view title in the viewDidLoad method of each custom viewController (somehow, setting it on the bar item didn't seem to work not did setting the image; the later may reflect an issue with my images however).
My original configuration was
TabViewController
NavController1 NavController2 NavController3 ...
| | |
CustomViewController1 CustomViewController2 CustomViewController3
My final configuration is now
TabViewController
NavController1 NavController2 NavController3 ...
| | |
iAdView1 iAdView2 iAdView3
| | |
CustomViewController1 CustomViewController2 CustomViewController3
In terms of view lifecycle, I should add that only the NavControllers are in existence at the time the updateiAd method is called.
The individual CustomViewControllers1/2/3/etc get created after the call completes.
The docs say that the whole subview hierarchy can be created in -loadView. But there's also this -viewDidLoad method which sounds nice to ovewrite for actually building the hierarchy, when the view loaded. I guess it's a matter of taste only. But maybe doing so in -viewDidLoad hast the advantage that the view controller already adjusted the frame of the view correctly to accomodate for the status bar or any other kind of bar like tab bar or tool bar?
viewDidLoad is called after the view hierarchy is built. loadView is supposed to build the hierarchy and set the view property if you are not loading from a NIB file.
viewDidLoad is also called after a memory warning if you're view got unloaded. When you get a memory warning viewDidUnload is called to give you a change to release objects that can be easily recreated in viewDidLoad.
Read the "Subclassing Notes" and "Memory Management" sections of the class description to better understand how it works.
I think the logic behind it is that in loadView you build elements, i.e. instantiate and allocate memory, this being the most costly action. So when [super loadView] has been called all the way up the ladder, all views are ready to be displayed and the expensive part is over.
In - (void) viewDidLoad you populate the views with data, viewDidLoad "know" all elements are ready to have text set on them, values, content etc.
UINavigationControllers etc. can benefit from knowing when everything is ready as to start animating view on to the screen. If you place all the instantiation/allocation in the viewDidLoad you force the controller to do everything, including being animated on screen, at the last moment. I don't know the exact details, but this is what I get from the documentation and the "life-cycle" of the UIViewController
I usually do it like this:
- (void)loadView {
[super loadView];
UIView *container = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 20.0f, 320.0f, 460.0f)];
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"bg02.png"]];
[container addSubview:imageView];
[imageView release];
UIImageView *background = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"bg_search.png"]];
[container addSubview:background];
[background release];
UILabel *textlabel = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, 10.0f, 200.0f, 20.0f)];
[self setLabel:textlabel];
[container addSubview:self.label];
[textlabel release];
[self setView:container];
[container release];
}
- (void)viewDidLoad {
[self.label setText:#"I am ready!"];
[super viewDidLoad];
}
I sometimes use the viewWillAppear to set data, if it is a view controller that sports modalViewControllers or pushes a new viewController where a user sets data that needs to be updated on the parent when popping the view again (e.g. a UITableViewController with a list of songs is pushed, the user selects a song and the controllers pops and the parent now displays the song title the user selected etc.) Any case wher the view goes on/off screen often, but needs to display newly changed data.
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];