How to create a custom timing function? - objective-c

I am busy with a custom animated transition between UIViewControllers and I like the the UIView to jump and then fill up the space similar to the following screenshot:
Now there isn't an "Option" I could create such an effect. Now I could create a keyframe animation with one key at the top and one in the center but that wouldn't feel really natural, it would feel robotic.
How would one approach this?
SOURCE (SO FAR)
- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext
{
UIViewController *fromVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
UIViewController *toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
UIView *container = [transitionContext containerView];
if ([fromVC isEqual:self])
{
[_activeCardView.superview bringSubviewToFront:_activeCardView];
[UIView animateKeyframesWithDuration:[self transitionDuration:transitionContext]
delay:0.0
options:UIViewKeyframeAnimationOptionCalculationModeCubic
animations:^{
[_activeCardView setFrame:CGRectMake(0.0, 0.0, toVC.view.bounds.size.width, toVC.view.bounds.size.height)];
}
completion:^(BOOL finished){
[container addSubview:toVC.view];
[transitionContext completeTransition:YES];
}];
}
else
{
[container addSubview:toVC.view];
[UIView animateWithDuration:[self transitionDuration:transitionContext]
animations:^{
[_activeCardView setFrame:_basicCardFrame];
}
completion:^(BOOL finished){
[transitionContext completeTransition:YES];
}];
}
}

For a smooth 'jump' animation you could just chain two animations with 'EaseInOut' curves.
[UIView animateWithDuration:<DURATION>/2 delay:<DELAY> options:UIViewAnimationOptionCurveEaseInOut animations:^(void) {
//move view up
}completion:^(BOOL finished) {
[UIView animateWithDuration:<DURATION>/2 delay:<DELAY> options:UIViewAnimationOptionCurveEaseInOut animations:^(void) {
//move view down
}completion:NULL];
}];

Related

setNavigationBarHidden with options

Is there a way to adjust the duration and curve of the setNavigationBarHidden method of a UINavigationController? It appears far too quickly and does not mesh with the other animations on my app.
You could create your own hide animation as follows:
[UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
self.navigationController.navigationBar.alpha = 0;
} completion:^(BOOL finished) {
[self.navigationController setNavigationBarHidden:YES animated:NO];
}];

Interactive UIViewController Transition with new "usingSpringWithDamping:initialSpringVelocity"-animation

I try to implement a interactive custom modal UIViewController transition using the new iOS7 APIs. Everything is working as desired as long as I don't use the new
+ (void)animateWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay usingSpringWithDamping:(CGFloat)dampingRatio initialSpringVelocity:(CGFloat)velocity options:(UIViewAnimationOptions)options animations:(void (^)(void))animations completion:(void (^)(BOOL finished))completion
method for animating the transition. It is working fine if I invoke the transition via a button. The problem occurs when the transition is interactive, driven by a GestureRecognzier. If I release my finger the animation is immediately cut of and won't finish. The same code is working if I use
animateWithDuration:delay:options:animations:completion:
instead.
Here is the code which animates the transition:
- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext {
UIViewController *fromViewController = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
UIViewController *toViewController = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
CGRect fullFrame = transitionContext.containerView.frame;
if (!self.dismissal) {
[transitionContext.containerView addSubview:fromViewController.view];
[transitionContext.containerView addSubview:toViewController.view];
fromViewController.view.frame = fullFrame;
toViewController.view.frame = CGRectMake(0, fullFrame.size.height, 0, 0);
[UIView animateWithDuration:[self transitionDuration:transitionContext] delay:0 usingSpringWithDamping:0.5 initialSpringVelocity:0.5 options:UIViewAnimationOptionTransitionNone animations:^{
//animation
toViewController.view.frame = CGRectMake(0,0, fullFrame.size.width, fullFrame.size.height);
} completion:^(BOOL finished) {
[transitionContext completeTransition:![transitionContext transitionWasCancelled]];
}];
} else {
[transitionContext.containerView addSubview:toViewController.view];
[transitionContext.containerView addSubview:fromViewController.view];
fromViewController.view.frame = fullFrame;
[UIView animateWithDuration:[self transitionDuration:transitionContext] delay:0 usingSpringWithDamping:.5 initialSpringVelocity:.5 options:0 animations:^{
fromViewController.view.frame = CGRectMake(0, fullFrame.size.height, fullFrame.size.width, fullFrame.size.height);
} completion:^(BOOL finished) {
[transitionContext completeTransition:![transitionContext transitionWasCancelled]];
}];
//This is working fine
// [UIView animateWithDuration:[self transitionDuration:transitionContext]/2 animations:^{
// fromViewController.view.frame = CGRectMake(0, fullFrame.size.height, fullFrame.size.width, fullFrame.size.height);
// } completion:^(BOOL finished) {
// [transitionContext completeTransition:![transitionContext transitionWasCancelled]];
// }];
}
This is the code behind the gesture recogniser:
#pragma mark - Gesture recognition
- (void)handlePan:(UIScreenEdgePanGestureRecognizer *)pgr
{
CGPoint translation = [pgr translationInView:pgr.view];
CGFloat percentage = fabs(translation.x / CGRectGetWidth(pgr.view.frame));
switch (pgr.state) {
case UIGestureRecognizerStateBegan:
self.interactionInProgress = YES;
[self.respondingVC proceedToNextViewController];
break;
case UIGestureRecognizerStateChanged: {
[self updateInteractiveTransition:percentage];
break;
}
case UIGestureRecognizerStateEnded:
if(percentage < 0.5) {
[self cancelInteractiveTransition];
} else {
[self finishInteractiveTransition];
}
self.interactionInProgress = NO;
break;
case UIGestureRecognizerStateCancelled:
[self cancelInteractiveTransition];
self.interactionInProgress = NO;
default:
break;
}
}
It looks like you're using UIPercentDrivenInteractiveTransition. When you call finishInteractiveTransition, UIPercentDriventInteractiveTransition does not call animateTransition.
You should override both updateInteractiveTransition and finishInteractiveTransition to update your view states.
All my attempts to begin an animation block inside an interactive transition have ended in failure. I finally at least got it to finish the animation by calling [self updateInteractiveTransition:1] in finishInteractiveTransition. Otherwise the views will be left in the state they were in and the transition never completes or the transition is treated as completed but your views are in strange places.

List of Buttons lighting up at random

The method im trying to achieve is set a button to 0.5 alpha then back to 1 in the space of three seconds. After its executed 5 time on the four buttons the block of code is finished. Im struggling to find a way in which this can be achieved becasue right now the block below will be an infinite loop when i want it to be only executed through once.
int rand=random()%5;
switch (rand) {
case 1:{
[UIView beginAnimations:NULL context:NULL];
[UIView setAnimationDuration:5.0];
[btnYellow setAlpha:0.5];
[btnYellow setAlpha:1];
[UIView commitAnimations];
}
break;
case 2:
[UIView beginAnimations:NULL context:NULL];
[UIView setAnimationDuration:5.0];
[btnRed setAlpha:0.5];
[btnRed setAlpha:1];
[UIView commitAnimations];
break;
case 3:
[UIView beginAnimations:NULL context:NULL];
[UIView setAnimationDuration:5.0];
[btnBlue setAlpha:1];
[UIView commitAnimations];
case 4:
[UIView beginAnimations:NULL context:NULL];
[UIView setAnimationDuration:5.0];
[btnGreen setAlpha:1];
[UIView commitAnimations];
break;
case 5:
[UIView beginAnimations:NULL context:NULL];
[UIView setAnimationDuration:5.0];
[btnYellow setAlpha:1];
[UIView commitAnimations];
break;
}
As you are setting up the button's alpha to 0.5 and then to 1 immediately, the button's alpha won't animate. You can get an idea this snippet
[UIView animateWithDuration:0.3 animations:^{
[your_btn setAlpha:0.5];
} completion:^(BOOL finished) {
if(finished)
[self performSelector:#selector(revertAlphaToOne) withObject:nil afterDelay:0.5];
}];
And in that revertAlphaToOne Method, you can revert the button's alpha to 1 as
[UIView animateWithDuration:0.3 animations:^{
[your_btn setAlpha:1.0];
} completion:nil
}];
Adjust the time variables according to your likings And/Or call the second snippet in the first block's completion block itself.
Well, I've been using this site for several years, and I was due for a nice thorough answer to give back.
I built a project and accomplished the functionality you desired. Some notes:
-The key is recursion! You need to animate the fade out (using the function I provided) and, upon completion, animating the fade back in using the same function. Once completed, exercise recursion and prepare to call itself (beginAnimations) until all ints=5.
-I decided to fade from 1->.5->1 because the .5 alpha was annoying me. Shouldn't be hard to switch that around if you want it reversed.
-To make sure no button fades more than fives times, you need to declare and increment an int corresponding to each button.
-Use arc4random(), not random(). Random is for debugging as you will have the same result every time.
-Keep your switch case's straight; was hard to understand what you wanted to be different between them. On this note, use breaks and a default statement! Good luck employing all this into your app.
.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[self.view setBackgroundColor:[UIColor blackColor]];
//declare and define button specifics
btnYellow = [UIButton buttonWithType: UIButtonTypeCustom];
[btnYellow setBackgroundColor: [UIColor yellowColor]];
btnYellow = [self buttonTraits:btnYellow];
[btnYellow setFrame: CGRectMake(20, 20, 280, 30)];
[btnYellow setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[btnYellow.titleLabel setFont:[UIFont boldSystemFontOfSize:14]];
btnRed = [UIButton buttonWithType: UIButtonTypeCustom];
[btnRed setBackgroundColor: [UIColor redColor]];
[btnRed setFrame: CGRectMake(20, 60, 280, 30)];
[btnRed setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[btnRed.titleLabel setFont:[UIFont boldSystemFontOfSize:14]];
btnBlue = [UIButton buttonWithType: UIButtonTypeCustom];
[btnBlue setFrame: CGRectMake(20, 100, 280, 30)];
[btnBlue setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[btnBlue.titleLabel setFont:[UIFont boldSystemFontOfSize:14]];
[btnBlue setBackgroundColor: [UIColor blueColor]];
btnGreen = [UIButton buttonWithType: UIButtonTypeCustom];
[btnGreen setFrame: CGRectMake(20, 140, 280, 30)];
[btnGreen setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[btnGreen.titleLabel setFont:[UIFont boldSystemFontOfSize:14]];
[btnGreen setBackgroundColor: [UIColor greenColor]];
//add buttons to the view
[self.view addSubview:btnYellow];
[self.view addSubview:btnRed];
[self.view addSubview:btnBlue];
[self.view addSubview:btnGreen];
//set the counting ints to 0
yellowCount = 0, redCount = 0, blueCount = 0, greenCount = 0;
//run through the animations the first time
[self beginAnimations];
}
-(void)beginAnimations
{
if (!(yellowCount==5 && redCount==5 && blueCount == 5 && greenCount == 5))
{
//if you want 5 buttons, define another one, then the next line would be int rand=random()%6;
int rand=((arc4random()%5)+1); //arc4random gives 0-3; add 1 for 1-4
switch (rand) {
case 1:
{
//make sure this button hasn't gone through the process 5 times already
if (yellowCount<5)
{
//increment the button's count
yellowCount++;
//set up animation with 1.5 second duration (alpha decline from 1->.5)
[UIView animateWithDuration:1.5 delay:0 options: UIViewAnimationOptionCurveEaseOut animations:^{
[btnYellow setAlpha:.5];
} completion:^(BOOL finished)
{
if(finished==TRUE)
{
[UIView animateWithDuration:1.5 delay:0 options: UIViewAnimationOptionCurveEaseOut animations:^{
[btnYellow setAlpha:1];
} completion:^(BOOL finished) {
if(finished==TRUE)
{
[self beginAnimations];
}
}];
}
}];
}
else
{
//restart the animation hoping to get another button that hasn't gone 5 times yet
[self beginAnimations];
}
}
break; //you forgot a break here. can cause troubles
case 2:
{
if (redCount<5)
{
redCount++;
[UIView animateWithDuration:1.5 delay:0 options: UIViewAnimationOptionCurveEaseOut animations:^
{
[btnRed setAlpha:.5];
} completion:^(BOOL finished)
{
if(finished==TRUE)
{
[UIView animateWithDuration:1.5 delay:0 options: UIViewAnimationOptionCurveEaseOut animations:^{
[btnRed setAlpha:1];
} completion:^(BOOL finished) {
if(finished==TRUE)
{
[self beginAnimations];
}
}];
}
}];
}
else
{
[self beginAnimations];
}
}
break;
case 3:
{
if (blueCount<5)
{
blueCount++;
[UIView animateWithDuration:1.5 delay:0 options: UIViewAnimationOptionCurveEaseOut animations:^
{
[btnBlue setAlpha:.5];
} completion:^(BOOL finished)
{
if(finished==TRUE)
{
[UIView animateWithDuration:1.5 delay:0 options: UIViewAnimationOptionCurveEaseOut animations:^{
[btnBlue setAlpha:1];
} completion:^(BOOL finished) {
if(finished==TRUE)
{
[self beginAnimations];
}
}];
}
}];
}
else
{
[self beginAnimations];
}
}
break; //you forgot another break here. can cause troubles
case 4:
{
if (greenCount<5)
{
greenCount++;
[UIView animateWithDuration:1.5 delay:0 options: UIViewAnimationOptionCurveEaseOut animations:^
{
[btnGreen setAlpha:.5];
} completion:^(BOOL finished)
{
if(finished==TRUE)
{
[UIView animateWithDuration:1.5 delay:0 options: UIViewAnimationOptionCurveEaseOut animations:^{
[btnGreen setAlpha:1];
} completion:^(BOOL finished) {
if(finished==TRUE)
{
[self beginAnimations];
}
}];
}
}];
}
else
{
[self beginAnimations];
}
}
break;
default:
{
//in case of an awry number, restart the process (be wary; infinite loop potential)
[self beginAnimations];
}
break; //it is of good practice to always have a default method in switch statements
}
}
else
{
//the process is complete
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
{
UIButton *btnYellow;
UIButton *btnRed;
UIButton *btnBlue;
UIButton *btnGreen;
int yellowCount;
int redCount;
int blueCount;
int greenCount;
}
#end
The problem is that in cases 1 and 2, you set the alpha value to 0.5 and then IMMEDIATELY back to 1. So when the animation starts, it is simply 1 and will remain so. Just delete the 2nd assignment, and the animation will change alpha to 0.5. PS: As already mentioned, the random number generated is from 0 to 4, and not from 1 to 5.

animateWithDuration not working

I'm trying to animate a view with some buttons and controllers for my main view into the screen from the right side of the screen. The problem is it doesn't animate, it just goes directly to the finished state.
This is my code:
UIStoryboard* storyBoard = [UIStoryboard storyboardWithName:#"MainStoryboard" bundle:nil];
options = [storyBoard instantiateViewControllerWithIdentifier:#"OptionsView"];
options.delegate = self;
[self.view addSubview:options.view];
options.view.center = CGPointMake(floor(total_width+options.view.frame.size.width/2)+10, floor(total_height/2));
[UIView animateWithDuration:0.5
delay:0.0
options: UIViewAnimationOptionCurveEaseOut
animations:^{
options.view.center = CGPointMake(floor(total_width-options.view.frame.size.width/2)+10, floor(total_height/2));
}
completion:^(BOOL finished){
NSLog(#"Done!");
}];
EDIT
To make things more strange, if I put this animation inside the completion block of another animation then this one works, but not the new one.
UIButton* boton = (UIButton*) sender;
[UIView animateWithDuration:5.0
delay:0.0
options: UIViewAnimationOptionCurveLinear
animations:^{
boton.alpha = 0.0;
//Jumps directly to 0, animation doesn't work
}
completion:^(BOOL finished){
[UIView animateWithDuration:0.5
delay:0.0
options: UIViewAnimationOptionCurveEaseInOut
animations:^{
options.view.center = CGPointMake(floor(total_width-options.view.frame.size.width/2)+10, floor(total_height/2));
//It works now, but it doesn't take 5 seconds to start, it starts right away
}
completion:^(BOOL finished){
NSLog(#"Done!");
}];
}];
The line before the animateWithDuration:... call directly assigns the center to the same value that you're animating to. Either remove that or assign the initial center value there. An animation that has the same start and end values obviously has no effect.

Handling Device orientation problem for swapped views

i'm doing an ipad application, in which i have say two views
mainview and aboutus view
on startup i put the mainview in the rootcontroller's view (the one that is added to the window) alone.
and there's a button on mainview, that, when pressed, will remove the mainview from superview and put the aboutusview instead. aboutus has a similar button that gets us back to mainview.
Now the problem lies in the rotation (orientation).
when i detect an orientation change, i update the displayed view. works fine. (for mainview and aboutusview)
But if i rotate once any view, and then then try to see the second view. it seems that the second view is not autosizing.
CODE in rootViewController:
- (void)viewDidLoad
{
[super viewDidLoad];
_currentOrientation=UIDeviceOrientationPortrait;
[self.view addSubview:_mainView];
[_splashView removeFromSuperview];
}
-(void)viewDidAppear:(BOOL)animated
{
_currentView = _mainView;
}
-(void)toggleMainPage
{
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:.5];
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:[self view] cache:YES];
[_infoView removeFromSuperview];
[self.view addSubview:_mainView];
_currentView=_mainView;
[self transformViewAccordingToOrientation:_currentOrientation];
[UIView commitAnimations];
}
-(void)toggleAboutPage
{
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:.5];
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:[self view] cache:YES];
[_mainView removeFromSuperview];
[self.view addSubview:_infoView];
_currentView=_infoView;
[self transformViewAccordingToOrientation:_currentOrientation];
[UIView commitAnimations];
}
-(void) transformViewAccordingToOrientation:(UIDeviceOrientation)toInterfaceOrientation
{
if(toInterfaceOrientation == UIDeviceOrientationPortrait)
{
[_mainBtnCustom setBackgroundImage:[UIImage imageNamed:#"main.png"] forState:UIControlStateNormal];
_infoImage.image = [UIImage imageNamed:#"about.png"];
}else
{
[_mainBtnCustom setBackgroundImage:[UIImage imageNamed:#"mainr.png"] forState:UIControlStateNormal];
_infoImage.image = [UIImage imageNamed:#"aboutr.png"];
}
}
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
[self transformViewAccordingToOrientation:toInterfaceOrientation];
}
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
_currentOrientation = [UIDevice currentDevice].orientation;
[self transformViewAccordingToOrientation:_currentOrientation];
}
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (_currentOrientation !=interfaceOrientation);
}
what am i doing wrong?