Custom segue, but leave the previous scene showing - objective-c

Imagine a custom segue ...
-(void)perform
{
UIView *sv = ((UIViewController *)self.sourceViewController).view;
UIView *dv = ((UIViewController *)self.destinationViewController).view;
UIWindow *window = [[[UIApplication sharedApplication] delegate] window];
[window insertSubview:dv aboveSubview:sv];
[dv coverFromRight:0 then:^
{
[self.sourceViewController
presentViewController:self.destinationViewController
animated:NO completion:nil];
}];
}
Which in fact, only PARTIALLY (!) covers the "underneath, previous" scene,
and in fact DOES NOT call "presentViewController", so, the "underneath, previous" scene in fact keeps operating normally.
-(void)perform
{
UIView *sv = ((UIViewController *)self.sourceViewController).view;
UIView *dv = ((UIViewController *)self.destinationViewController).view;
UIWindow *window = [[[UIApplication sharedApplication] delegate] window];
[window insertSubview:dv aboveSubview:sv];
[dv coverButOnlyHalfWay:0 then:^
{
}];
}
Essentially, is this possible?
In fact, I've found from experiment the above works (!!). BUT when you come to the custom unwind segue, it does not work: everything crashes. (Perhaps as you'd expect.)
What's the situation? is there a way to make a custom segue, which, covers only say half the "original, underneath" scene and leaves that scene running?
(I appreciate you can just implement this using a container view, but it's not as clean as a whole segue scene.)

Why use a segue? You can just add your view as a subview and position it correct using CGRectMake, this would be much easier.
// Size Your View with X, Y coordinates
[viewController.view setFrame:CGRectMake(0, 0, 320, 192)];
[self.view addSubview:viewController.view];
[viewController didMoveToParentViewController:self];
[self addChildViewController:viewController];

Related

Restore pre-iOS7 UINavigationController pushViewController animation

So. Just started transitioning my IOS code to IOS7, and ran into a bit of problem.
I've got a UINavigationController, which has child ViewControllers and I'm using pushViewController to display the next views. To create a parallax animation with a set of images, if customized the UINavigationController to animate a set of UIImageViews and my child ViewControllers all have a self.backgroundColor = [UIColor clearColor], transparency.
Since iOS7, the way the UINavController animates it child vc's, is updated, by partially moving the current view controller and on top pushing the new viewcontroller, my parallax animation looks crap. I see the previous VC move a bit and then disappear. Is there any way I can restore the previous UINavigationController pushViewController animation? I can't seem to find this in the code.
WelcomeLoginViewController* welcomeLoginViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"WelcomeLogin"];
[self.navigationController pushViewController:welcomeLoginViewController animated:YES];
Even tried using:
[UIView animateWithDuration:0.75
animations:^{
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[self.navigationController pushViewController:welcomeLoginViewController animated:NO];
[UIView setAnimationTransition:<specific_animation_form> forView:self.navigationController.view cache:NO];
}];
Does anyone have any clue?
I managed to workaround the new transition type by creating a category for UINavigationController. In my case I needed to revert it to the old transition style because I have transparent viewControllers that slide over a static background.
UINavigationController+Retro.h
#interface UINavigationController (Retro)
- (void)pushViewControllerRetro:(UIViewController *)viewController;
- (void)popViewControllerRetro;
#end
UINavigationController+Retro.m
#import "UINavigationController+Retro.h"
#implementation UINavigationController (Retro)
- (void)pushViewControllerRetro:(UIViewController *)viewController {
CATransition *transition = [CATransition animation];
transition.duration = 0.25;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
transition.type = kCATransitionPush;
transition.subtype = kCATransitionFromRight;
[self.view.layer addAnimation:transition forKey:nil];
[self pushViewController:viewController animated:NO];
}
- (void)popViewControllerRetro {
CATransition *transition = [CATransition animation];
transition.duration = 0.25;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
transition.type = kCATransitionPush;
transition.subtype = kCATransitionFromLeft;
[self.view.layer addAnimation:transition forKey:nil];
[self popViewControllerAnimated:NO];
}
#end
I have the same problem with clear background colors and crappy animations, so I create custom transitioning for ViewController with new iOS7 API. All you need is simply set a delegate for your navigation controller:
// NavigationController does not retain delegate, so you should hold it.
self.navigationController.delegate = self.navigationTransitioningDelegate;
Just add this files into your project: MGNavigationTransitioningDelegate.
I had a problem where when UIViewController A did a pushViewController to push UIViewController B, the push animation would stop at about 25%, halt, and then slide B in the rest of the way.
This DID NOT happen on iOS 6, but as soon as I started using iOS 7 as the base SDK in XCode 5, this started happening.
The fix is that view controller B did not have a backgroundColor set on its root view (the root view is the one that is the value of viewController.view, that you typically set in loadView). Setting a backgroundColor in that root view's initializer fixed the problem.
I managed to fix this as follows:
// CASE 1: The root view for a UIViewController subclass that had a halting animation
- (id)initWithFrame:(CGRect)frame
{
if ((self = [super initWithFrame:frame])) {
// Do some initialization ...
// self.backgroundColor was NOT being set
// and animation in pushViewController was slow and stopped at 25% and paused
}
return self;
}
// CASE 2: HERE IS THE FIX
- (id)initWithFrame:(CGRect)frame
{
if ((self = [super initWithFrame:frame])) {
// Do some initialization ...
// Set self.backgroundColor for the fix!
// and animation in pushViewController is no longer slow and and no longer stopped at 25% and paused
self.backgroundColor = [UIColor whiteColor]; // or some other non-clear color
}
return self;
}
First of, I'm not using Storyboard. I tried using UINavigationController+Retro. For some reason, the UINavigationController is having a hard time releasing the UIViewController at the top of the stack. Here's the solution that works for me using iOS 7 custom transition.
Set delegate to self.
navigationController.delegate = self;
Declare this UINavigationControllerDelegate.
- (id<UIViewControllerAnimatedTransitioning>)navigationController (UINavigationController *)navigationController
animationControllerForOperation:(UINavigationControllerOperation)operation
fromViewController:(UIViewController *)fromVC
toViewController:(UIViewController *)toVC
{
TransitionAnimator *animator = [TransitionAnimator new];
animator.presenting = YES;
return animator;
}
Note that it'll only get called when animated is set to YES. For example
[navigationController pushViewController:currentViewController animated:YES];
Create the animator class extending NSObject. I called mine TransitionAnimator, which was modified from TeehanLax's TLTransitionAnimator inside UIViewController-Transitions-Example.
TransitionAnimator.h
#import <Foundation/Foundation.h>
#interface TransitionAnimator : NSObject <UIViewControllerAnimatedTransitioning>
#property (nonatomic, assign, getter = isPresenting) BOOL presenting;
#end
TransitionAnimator.m
#import "TransitionAnimator.h"
#implementation TransitionAnimator
- (NSTimeInterval)transitionDuration:(id <UIViewControllerContextTransitioning>)transitionContext {
return 0.5f;
}
- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext{
UIViewController *fromVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
UIViewController *toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
if (self.presenting) {
//ANIMATE VC ENTERING FROM THE RIGHT SIDE OF THE SCREEN
[transitionContext.containerView addSubview:fromVC.view];
[transitionContext.containerView addSubview:toVC.view];
toVC.view.frame = CGRectMake(0, 0, 2*APP_W0, APP_H0); //SET ORIGINAL POSITION toVC OFF TO THE RIGHT
[UIView animateWithDuration:[self transitionDuration:transitionContext]
animations:^{
fromVC.view.frame = CGRectMake(0, (-1)*APP_W0, APP_W0, APP_H0); //MOVE fromVC OFF TO THE LEFT
toVC.view.frame = CGRectMake(0, 0, APP_W0, APP_H0); //ANIMATE toVC IN TO OCCUPY THE SCREEN
} completion:^(BOOL finished) {
[transitionContext completeTransition:YES];
}];
}else{
//ANIMATE VC EXITING TO THE RIGHT SIDE OF THE SCREEN
}
}
#end
Use presenting flag to set the direction you want to animate or which ever condition you prefer. Here's the link to Apple reference.
Thanks guys for the feedback. Found a solution in completely recreating the UINavigationController's behavior. When I was nearly finished I ran into Nick Lockwood's solution:
https://github.com/nicklockwood/OSNavigationController
OSNavigationController is a open source re-implementation of UINavigationController. It currently features only a subset of the functionality of UINavigationController, but the long-term aim is to replicate 100% of the features.
OSNavigationController is not really intended to be used as-is. The idea is that you can fork it and then easily customize its appearance and behaviour to suit any special requirements that your app may have. Customizing OSNavigationController is much simpler than trying to customize UINavigationController due to the fact that the code is open and you don't need to worry about private methods, undocumented behavior, or implementation changes between versions.
By overriding my UINavigationController with his code, I was able to work with background images in UINavigationcontrollers
Thanks!
Simply add in:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
This:
[[self window] setBackgroundColor:[UIColor whiteColor]];
The final result:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions (NSDictionary *)launchOptions {
[[self window] setBackgroundColor:[UIColor whiteColor]];
// Override point for customization after application launch.
return YES;
}
Apparently in iOS7 there's a new way define your own custom UIViewController transitions. Look in the docs for UIViewControllerTransitioningDelegate. Also, here's a link to an article about it: http://www.doubleencore.com/2013/09/ios-7-custom-transitions/
Swift 5 implementation of Arne's answer:
extension UINavigationController {
func pushViewControllerLegacyTransition(_ viewController: UIViewController) {
let transition = CATransition()
transition.duration = 0.25
transition.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
transition.type = .push
transition.subtype = .fromRight
view.layer.add(transition, forKey: nil)
pushViewController(viewController, animated: false)
}
func popViewControllerLegacyTransition() {
let transition = CATransition()
transition.duration = 0.25
transition.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
transition.type = .push
transition.subtype = .fromLeft
view.layer.add(transition, forKey: nil)
popViewController(animated: false)
}
}
Found another great resource to help out:
http://www.teehanlax.com/blog/custom-uiviewcontroller-transitions
Using iOS7 TLTransitionAnimator to create custom animations
I voted for #Arne's answer, because I find it the most elegant solution to this problem. I would just like to add some code in order to answer to #Bill's problem from his comment on #Arne's solution. Here's comment quote:
Thanks, this works for me. However, when the user taps the Back
button, it reverts to the busted animation (because the back button
doesn't call popViewControllerRetro). – Bill Oct 3 at 12:36
In order to call popViewControllerRetro when back button is pressed, there's a small hack you can perform in order to achieve this. Go into your pushed view controller, import UIViewController+Retro.h and add this code in your viewWillDisappear method:
- (void)viewWillDisappear:(BOOL)animated {
if ([self.navigationController.viewControllers indexOfObject:self] == NSNotFound) {
[self.navigationController popViewControllerRetro];
}
[super viewWillDisappear:animated];
}
This if statement will detect when Back button is pressed and will call popViewControllerRetro from category class.
Best regards.

addSubview outside the view

I have a viewcontroller that via "[self.view addSubview: secondView.view]," adds a second view. The problem is that the second view is added outside half.
secondView = [[SecondView alloc] initWithFrame: CGRectMake (-160, 0, 320, 460)];
[self.view addSubview: secondView.view]; "
I have noticed, however, that the part before the 0 (-160) is not interagibile. Is this normal? is there a way to solve?
Thank you!
You can allow subviews to receive touches outside of the parent's bounds by overriding pointInside:withEvent: for the parent view.
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
BOOL pointInside = NO;
// step through our subviews' frames that exist out of our bounds
for (UIView *subview in self.subviews)
{
if(!CGRectContainsRect(self.bounds, subview.frame) && [subview pointInside:[self convertPoint:point toView:subview] withEvent:event])
{
pointInside = YES;
break;
}
}
// now check inside the bounds
if(!pointInside)
{
pointInside = [super pointInside:point withEvent:event];
}
return pointInside;
}
I fear that given the way the UIResponder chain works, what you want is not directly possible (the superview will only pass to its subviews the events that it recognizes as affecting itself).
On the other hand, if you really need to have this view outside of its parent's frame, you could associate a gesture recognizer (reference) to the subview. Indeed, gesture recognizers are handled outside the normal touch event dispatching and it should work.
Try this for a tap:
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(handleSingleTap:)];
[secondView addGestureRecognizer:singleTap];

ModalViewController for Single Subview

Ok, so bear with me: as this is an Objective-C related question, there's obviously a lot of code and subclassing. So here's my issue. Right now, I've got an iPad app that programmatically creates a button and two colored UIViews. These colored UIViews are controlled by SubViewControllers, and the entire thing is in a UIView controlled by a MainViewController. (i.e. MainViewController = [UIButton, SubViewController, SubViewController])
Now, all of this happens as it should, and I end up with what I expect (below):
However, when I click the button, and the console shows "flipSubView1", nothing happens. No modal view gets shown, and no errors occur. Just nothing. What I expect is that either subView1 or the entire view will flip horizontally and show subView3. Is there some code that I'm missing that would cause that to happen / is there some bug that I'm overlooking?
viewtoolsAppDelegate.m
#implementation viewtoolsAppDelegate
#synthesize window = _window;
#synthesize mvc;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
mvc = [[MainViewController alloc] initWithFrame:self.window.frame];
[self.window addSubview:mvc.theView];
[self.window makeKeyAndVisible];
return YES;
}
MainViewController.m
#implementation MainViewController
#synthesize theView;
#synthesize subView1, subView2, subView3;
- (id)initWithFrame:(CGRect) frame
{
theView = [[UIView alloc] initWithFrame:frame];
CGRect sV1Rect = CGRectMake(frame.origin.x+44, frame.origin.y, frame.size.width-44, frame.size.height/2);
CGRect sV2Rect = CGRectMake(frame.origin.x+44, frame.origin.y+frame.size.height/2, frame.size.width-44, frame.size.height/2);
subView1 = [[SubViewController alloc] initWithFrame:sV1Rect andColor:[UIColor blueColor]];
subView2 = [[SubViewController alloc] initWithFrame:sV2Rect andColor:[UIColor greenColor]];
subView3 = [[SubViewController alloc] initWithFrame:sV1Rect andColor:[UIColor redColor]];
[theView addSubview:subView1.theView];
[theView addSubview:subView2.theView];
UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[aButton addTarget:self action:#selector(flipSubView1:) forControlEvents:(UIControlEvents)UIControlEventTouchDown];
[aButton setFrame:CGRectMake(0, 0, 44, frame.size.height)];
[theView addSubview:aButton];
return self;
}
- (void)flipSubView1:(id) sender
{
NSLog(#"flipSubView1");
[subView3 setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
[subView1 presentModalViewController:subView3 animated:YES];
}
SubViewController.m
#implementation SubViewController
#synthesize theView;
- (id)initWithFrame:(CGRect)frame andColor:(UIColor *)color
{
theView = [[UIView alloc] initWithFrame:frame];
theView.backgroundColor = color;
return self;
}
TLDR: modal view not working. should see flip. don't.
It doesn't look like you're setting the 'view' property of the MainViewController anywhere, just 'theView'. The controllers view delegate must be connected to the root view it displays for it to work properly. You'll need to correct that on the Sub View Controller impl as well. If you want all the plumbing that framework classes bring, you have to set things up the way they expect.
Also, you're calling presentModalViewController on one of the sub view controllers; change that to call [self presentModalViewController:...], since the MainViewController is the one which will 'own' the modal view.
I think if you fix those points, you'll find -presentModalViewController will work.

Getting reference to the top-most view/window in iOS application

I'm creating a reusable framework for displaying notifications in an iOS application. I'd like the notification views to be added over the top of everything else in the application, sort of like a UIAlertView. When I init the manager that listens for NSNotification events and adds views in response, I need to get a reference to the top-most view in the application. This is what I have at the moment:
_topView = [[[[UIApplication sharedApplication] keyWindow] subviews] lastObject];
Would this work for any iOS application or is their a safer/better way to get the top view?
Whenever I want to display some overlay on top of everything else, I just add it on top of the Application Window directly:
[[[UIApplication sharedApplication] keyWindow] addSubview:someView]
There are two parts of the problem: Top window, top view on top window.
All the existing answers missed the top window part. But [[UIApplication sharedApplication] keyWindow] is not guaranteed to be the top window.
Top window. It is very unlikely that there will be two windows with the same windowLevel coexist for an app, so we can sort all the windows by windowLevel and get the topmost one.
UIWindow *topWindow = [[[UIApplication sharedApplication].windows sortedArrayUsingComparator:^NSComparisonResult(UIWindow *win1, UIWindow *win2) {
return win1.windowLevel - win2.windowLevel;
}] lastObject];
Top view on top window. Just to be complete. As already pointed out in the question:
UIView *topView = [[topWindow subviews] lastObject];
Usually that will give you the top view, but there's no guarantee that it's visible to the user. It could be off the screen, have an alpha of 0.0, or could be have size of 0x0 for example.
It could also be that the keyWindow has no subviews, so you should probably test for that first. This would be unusual, but it's not impossible.
UIWindow is a subclass of UIView, so if you want to make sure your notification is visible to the user, you can add it directly to the keyWindow using addSubview: and it will instantly be the top most view. I'm not sure if this is what you're looking to do though. (Based on your question, it looks like you already know this.)
Actually there could be more than one UIWindow in your application. For example, if a keyboard is on screen then [[UIApplication sharedApplication] windows] will contain at least two windows (your key-window and the keyboard window).
So if you want your view to appear ontop of both of them then you gotta do something like:
[[[[UIApplication sharedApplication] windows] lastObject] addSubview:view];
(Assuming lastObject contains the window with the highest windowLevel priority).
I'm sticking to the question as the title states and not the discussion. Which view is top visible on any given point?
#implementation UIView (Extra)
- (UIView *)findTopMostViewForPoint:(CGPoint)point
{
for(int i = self.subviews.count - 1; i >= 0; i--)
{
UIView *subview = [self.subviews objectAtIndex:i];
if(!subview.hidden && CGRectContainsPoint(subview.frame, point))
{
CGPoint pointConverted = [self convertPoint:point toView:subview];
return [subview findTopMostViewForPoint:pointConverted];
}
}
return self;
}
- (UIWindow *)topmostWindow
{
UIWindow *topWindow = [[[UIApplication sharedApplication].windows sortedArrayUsingComparator:^NSComparisonResult(UIWindow *win1, UIWindow *win2) {
return win1.windowLevel - win2.windowLevel;
}] lastObject];
return topWindow;
}
#end
Can be used directly with any UIWindow as receiver or any UIView as receiver.
If you are adding a loading view (an activity indicator view for instance), make sure you have an object of UIWindow class. If you show an action sheet just before you show your loading view, the keyWindow will be the UIActionSheet and not UIWindow. And since the action sheet will go away, the loading view will go away with it. Or that's what was causing me problems.
UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
if (![NSStringFromClass([keyWindow class]) isEqualToString:#"UIWindow"]) {
// find uiwindow in windows
NSArray *windows = [UIApplication sharedApplication].windows;
for (UIWindow *window in windows) {
if ([NSStringFromClass([window class]) isEqualToString:#"UIWindow"]) {
keyWindow = window;
break;
}
}
}
If your application only works in portrait orientation, this is enough:
[[[UIApplication sharedApplication] keyWindow] addSubview:yourView]
And your view will not be shown over keyboard and status bar.
If you want to get a topmost view that over keyboard or status bar, or you want the topmost view can rotate correctly with devices, please try this framework:
https://github.com/HarrisonXi/TopmostView
It supports iOS7/8/9.
Just use this code if you want to add a view above of everything in the screen.
[[UIApplication sharedApplication].keyWindow addSubView: yourView];
try this
UIWindow *window = [[[UIApplication sharedApplication] windows] lastObject];
UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
if (![NSStringFromClass([keyWindow class]) isEqualToString:#"UIWindow"]) {
NSArray *windows = [UIApplication sharedApplication].windows;
for (UIWindow *window in windows) {
if ([NSStringFromClass([window class]) isEqualToString:#"UIWindow"]) {
keyWindow = window;
break;
}
}
}

viewWillAppear-related problem

Without giving you all my code examples, I'll made this quick.
Has this ever happened to one of you to get viewWillAppear called only the first time it shows up?
I have this problem with all my view.
For example: When my app starts, I get to the StartView which is a main menu. (viewWillAppear gets called) then I press on one button that'll show a navigation controller (viewWillAppear gets called). Then I get back to the main menu (it does not get called) and then I press on the same navigation controller again and it does not get called.
It would be awesome if someone could points me somewhere, I've been searching for this since two days now...
Also if you need more code samples, I can give you some.
For further reading:
That's how I call my navigation controller:
PremierSoinsAppDelegate *AppDelegate = (PremierSoinsAppDelegate *)[[UIApplication sharedApplication] delegate];
UIView *newView = [AppDelegate.navigationController view];
[newView setFrame:CGRectMake(320.0f, 0.0f, 320.0f, 480.0f)];
[UIView beginAnimations:#"RootViewController" context:nil];
[UIView setAnimationDuration:0.3];
newView setFrame:CGRectMake(0.0f, 0.0f, 320.0f, 480.0f)];
UIView commitAnimations];
[AppDelegate.window addSubview:newView];
[AppDelegate.window makeKeyAndVisible];
And that's how I show my menu back:
PremierSoinsAppDelegate *AppDelegate = (PremierSoinsAppDelegate *)[[UIApplication sharedApplication] delegate];
UIView *newView = [AppDelegate.startViewController view];
newView setFrame:CGRectMake(-320.0f, 0.0f, 320.0f, 480.0f)];
UIView beginAnimations:#"StartViewController" context:nil];
UIView setAnimationDuration:0.3];
newView setFrame:CGRectMake(0.0f, 0.0f, 320.0f, 480.0f)];
[UIView commitAnimations];
[AppDelegate.window addSubview:newView];
[AppDelegate.window makeKeyAndVisible];
Thanks A LOT.
You can implement the UINavigationControllerDelegate in your Nav Controller to propagate the viewWillAppear: messages down. You can implement the message like this:
- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
if ([viewController respondsToSelector:#selector(viewDidAppear:)]) {
[viewController viewDidAppear:animated];
}
}
Note that this is the viewDidAppear and not ViewWillAppear version, but they're basically the same.
However, you should note that the fact that you need to do this may be a sign that something else is wrong in your controller/view code and you might want to reask the question giving us more context to answer it. In particular, I'm assuming that somewhere outside of the code you're giving us, you're pushing and popping view controllers as per usual for a Nav Controller.
viewWill/DidAppear: will only be called when using a UINavigationController or UITabBarController (or really any system-provided-viewControlller managing class) to manipulate views. If you're manually doing this (as you seem to do in your second code snippet, these messages won't get sent.