iOS: UIView Animation Refactoring - ios

Whilst playing around with UIView animation, I came across a situation where I think some refactoring is needed:
The following views whose opacity are initially set to 0.0f.
Ex:
[UIView animateWithDuration:1.0f
animations:^
{
firstView.layer.opacity = 1.0f;
}
completion:^(BOOL finished)
{
[UIView animateWithDuration:1.0f
animations:^
{
secondView.layer.opacity = 1.0f;
firstView.layer.opacity = 0.0f;
}
completion:^(BOOL finished)
{
[UIView animateWithDuration:1.0f
animations:^
{
thirdView.layer.opacity = 1.0f;
secondView.layer.opacity = 0.0f;
}
completion:^(BOOL finished)
{
thirdView.layer.opacity = 0.0f;
}];
}];
}];
All 3 views are just subclass of UIView's, which are added as subviews of the main view.
This simply animates the opacity of the first view to 1.0f and then that of the second view, and then that of the third view.
Simple. Nothing special here.
My Question is:
What if I had more views, let say 100, that I wanted to perform the same action (same sequence of animation), this block of code would expand and expand.
So for the sake of refactoring and being adhered to good practice of writing code, I thought may be this could be done with less code via the use of a method and perhaps a loop.
Could you enlighten me on this in regards to refactoring; in addition, would dispatch_apply be useful here along with the refactoring process if a loop is needed?

If you wanted to animate 100 images, you would probably want to use 2 views and load alternating images into each one. I recently created a sample app on github that does exactly that:
Animating UIImages with cross-fade opacity changing

Related

How to force a view animation to finish before executing sendSubviewToBack?

I am building a page browser that animates pages as 'sheets of paper' being pulled on top of off a stack of papers. In order to keep smooth animations I use 3 UIViews which are stacked on top of each other. These three views hold the current page (on top), the previous page (in the middle) and the next page (at the bottom).
In the code below, I want to drag the top view off to the right, revealing the previous page underneath. This works fine. However, after that I need to move the top page to the bottom of the stack, in order to prepare the stack of three views for the next time the user does a page flip. I use the sendSubviewToBack method for this.
My problem is that ViewSample[Top] is sent to the bottom of the stack as soon as the animation starts. How can I enforce the animation to finish (so that ViewSample[Top] has moved out of the screen completely) before it is sent to the bottom of the stack?
ViewSample[Top].center = CGPointMake(x,y);
[UIView animateWithDuration:0.5
animations:^
{
ViewSample[Top].center = CGPointMake(x+w,y); //slide away to the right
}
completion:^(BOOL finished)
{
}
];
[self.MainView sendSubviewToBack:ViewSample[Top]];
EDIT
i just ran into a very peculiar behaviour which has to do with my problem.
I followed your advice, and found that the behaviour in the 'finished' section of the animation depends on the value of the variable 'top' when it is set AFTERWARDS:
ViewSample[Top].center = CGPointMake(x,y);
[UIView animateWithDuration:0.5
animations:^
{
ViewSample[Top].center = CGPointMake(x+w,y); //slide away to the right
}
completion:^(BOOL finished)
{ [self.MainView sendSubviewToBack:ViewSample[Top]];
}
];
Top++; // THIS COMMAND AFFECTS THE LINE ABOVE!!!
In other words, when I add the line 'Top++;' another View is moved back on the stack, even though the statement sendSubviewToBack came first. This is very confusing to me. Does this make sense? Is it a bug?
The other answers correctly identified the issue. What you're running into with your updated code is a problem of execution order:
Because completion is executed only after the animation completes, your code actually executes in this order:
ViewSample[Top].center = CGPointMake(x,y);
ViewSample[Top].center = CGPointMake(x+w,y);
Top++;
[self.MainView sendSubviewToBack:ViewSample[Top]];
There are two possible solutions. You can either store the view in a variable so you have the same view in all your calls, or you can delay setting the value of Top until completion.
Option 1
UIView *viewMovingFromTopToBottom = ViewSample[Top];
viewMovingFromTopToBottom.center = CGPointMake(x,y);
[UIView animateWithDuration:0.5 animations:^{
viewMovingFromTopToBottom.center = CGPointMake(x+w,y); //slide away to the right
} completion:^(BOOL finished) {
[self.MainView sendSubviewToBack:viewMovingFromTopToBottom];
}];
Top++;
// Other code that depends on the new value of Top...
Option 2
ViewSample[Top].center = CGPointMake(x,y);
[UIView animateWithDuration:0.5 animations:^{
ViewSample[Top].center = CGPointMake(x+w,y); //slide away to the right
} completion:^(BOOL finished) {
[self.MainView sendSubviewToBack:ViewSample[Top]];
Top++;
// Other code that depends on the new value of Top...
}];
Which option makes the most sense to you depends on what you're doing. If you're chaining animations together, you may want to move most of your code into the completion block to delay it until the slide animation completes. If you have a lot of work that needs to be done right away without dependencies on animation, you may want to use option 1 to configure you animations and move on. Or you may want a mix.
Use the completion block:
ViewSample[Top].center = CGPointMake(x,y);
[UIView animateWithDuration:0.5
animations:^
{
ViewSample[Top].center = CGPointMake(x+w,y); //slide away to the right
}
completion:^(BOOL finished)
{
[self.MainView sendSubviewToBack:ViewSample[Top]];
}
];
Brian Nickel's first suggestion (local variable) did the trick. However, there was a caveat: you have to be careful in the order of statements. This does not work:
[self.MainView addSubview:LocalView];
LocalView = View[1];
...whereas this does:
LocalView = View[1];
[self.MainView addSubview:LocalView];
I first had the top version, which just makes the blank view appear.
So a working approach is to use three global views to do the page caching, and use two local views for the animation. The local views are stacked in the appropriate order, copy the data from the global views and then perform the animation.

UIView progressive animation

The standard UIView animateWithDuration: block works great for animations that have require a single animation effect, i.e. resize and/or move.
Is there a way to make the animation progressive, such that the animation starts slow, and gains speed as it progresses?
I could try nested animateWithDuration: blocks, placing subsequent blocks in the completion handler, but that way the animation is a little 'ragged'. I wish to make the animation smooth.
One idea that comes to mind is that I create a recursive function as follows:
- (void) animateToYOrigin:(CGFloat)yOrigin{
if (myView.frame.origin.y < 1){
[UIView animateWithDuration:0.1
animations:^{
CGRect rect = myView.frame;
rect.origin.y = yOrigin;
myView.frame = rect;
} completion:^(BOOL finished) {
[self animateToYOrigin:yOrigin /2];
}];
}
}
I am looking for a refined solution.
You can use
[UIView animateWithDuration:time
delay:delay
options:OPTION_HERE
animations:anims
completion:completion]
method and pass UIViewAnimationOptions where it says OPTION_HERE. You can use basic ease in/out options by default. If you need more options you can check out this git repo. In MTTimingFuncations.h/c you can find multiple options you can pass.

iOS Graphic Appear and Fade Out with Alpha

I've been reading about UIView animateWithDuration which I'm trying to use so when a button is pressed a graphic appears then slowly fades out (i.e. alpha is set to 0).
I'm using the code below in my viewdidload just for test purposes however its not working:
[UIView animateWithDuration:10 animations:^{
self.completeImage.alpha = 1.0;
self.completeImage.alpha = 0.5;
self.completeImage.alpha = 0.0;
}];
Any ideas?
Thanks.
That is not working because automatically it sets the alpha to 0.0;
The 3 lines of code are executed at the same time (one after the other).
The proper way to use the UView animation block it is like this:
self.completeImage.alpha = 0.0;
[UIView animateWithDuration:2.0
animations:^{
// do first animation
self.completeImage.alpha = 1.0;
}
completion:^(BOOL finished){
[UIView animateWithDuration:2.0
animations:^{
// do second animation
self.completeImage.alpha = 0.0;
}
completion:^(BOOL finished){
;
}];
}];
Hope this achieve what you are looking for.
In addition:
" I'm trying to use so when a button is pressed a graphic appears
then slowly fades out (i.e. alpha is set to 0)."
As per your above information in the question, addition of the code in viewDidLoad will not prove fruitful. You need to add this code in the action target method of your button in order to play the animation on click of a button. Generally if you're using the nib, then the action method will be like below:
-(IBAction)on_pressing_my_button:(id)sender
{
///your animation code goes here..
}

Weird behaviour happens when using UIView animate and CGAffineTransform

I created some animations in my project. Basically, I use UIView animate and CGAffineTransform, but a very strange thing happened and I have no idea. Hope someone can help me solve this problem. Thanks in advance.
This is the strange thing:
After the user clicks on a button, the button slides off screen and another two buttons slide on the screen (I just changed the center point of these buttons to achieve this animation). And, some time later, a view on the screen start shaking (I use CGAffineTransform to achieve this).
At this moment, the strange thing happens - the button that previous slid off screen show up at its original position again and the other two buttons disappear (No animation, just shows up and disappear).
The following is the related code,
1) Button slide off and slide in animation related code
- (IBAction)start:(id)sender
{
// 1. Slide in cancel and pause button
[UIView animateWithDuration:0.5f animations:^{
[startButton setCenter:CGPointMake(startButton.center.x + 300.0f, startButton.center.y)];
[cancelButton setCenter:CGPointMake(cancelButton.center.x + 300.0f, cancelButton.center.y)];
[pauseButton setCenter:CGPointMake(pauseButton.center.x + 300.0f, pauseButton.center.y)];
} completion:^(BOOL finished) {
if (finished) {
NSLog(#"Move finished");
}
}];
}
2) The view shaking animation related code
- (void)shakeView:(UIView *)viewToShake
{
CGFloat t = 2.0;
CGAffineTransform translateRight = CGAffineTransformTranslate(CGAffineTransformIdentity, t, 0.0);
CGAffineTransform translateLeft = CGAffineTransformTranslate(CGAffineTransformIdentity, -t, 0.0);
viewToShake.transform = translateLeft;
[UIView animateWithDuration:0.07 delay:0.0 options:UIViewAnimationOptionAutoreverse|UIViewAnimationOptionRepeat animations:^{
[UIView setAnimationRepeatCount:2.0];
viewToShake.transform = translateRight;
} completion:^(BOOL finished) {
if (finished) {
[UIView animateWithDuration:0.05 delay:0.0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
viewToShake.transform = CGAffineTransformIdentity;
} completion:nil];
}
}];
}
This isn't weird, it's a common problem with
auto layout. If you move UI elements by changing frames, then as soon as something else takes place that requires laying out views, the moved views will revert to the position defined by their constraints. To fix it, you either need to turn off auto layout, or do your animations by changing constraints not frames.
I have tried your code in my test project. The problem is probably because you are using Autolayout in your xib.
Please checking your xib file and uncheck the Autolayout property.

How to cross-fade a UIScrollView back to the beginning

I have a horizontally-scrolling paging UIScrollView in an iPad app, containing lots of pages. On the last page, I tap on a button on the screen to reset back to page 1. I would like to be able to cross-dissolve this transition, but it doesn't seem to work:
[UIView transitionWithView:self.view duration:1.0 options:UIViewAnimationOptionTransitionCrossDissolve|UIViewAnimationOptionAllowAnimatedContent animations:^{
pagingScrollView.contentOffset = CGPointZero;
} completion:^(BOOL finished) {
[self refreshPages];
}];
I read that adding UIViewAnimationOptionAllowAnimatedContent will allow all content to transition, but it doesn't work. Instead, the screen cross-dissolves to the background colour, and when the transition is complete, the first page just appears.
you cannot fade-out a UIView (the scroller) AND simultaneously fade-in the same view...
you could just using different UIViews...
what you can do is:
1) fadeOut the scroller in the current position (to the backGround)
2) while the scroller is invisible, move it to the right position (with no animation)
3) fadeIn the scroller from the backGround
something like:
// START FIRST PART OF ANIMATION
[UIView animateWithDuration:0.5 delay:0.0 options: options:UIViewAnimationOptionTransitionCrossDissolve|UIViewAnimationOptionAllowAnimatedContent animations:^{
pagingScrollView.alpha = 0;
} completion:^(BOOL finished) {
// FIRST PART ENDED
// MOVE SCROLLER (no animation)
pagingScrollView.contentOffset = CGPointZero;
// START SECOND PART OF ANIMATION
[UIView animateWithDuration:0.5 delay:0.0 options: options:UIViewAnimationOptionTransitionCrossDissolve|UIViewAnimationOptionAllowAnimatedContent animations:^{
// fadeIn - animated
pagingScrollView.alpha = 1;
} completion:^(BOOL finished) {
// ANIMATION ENDED
[self refreshPages];
}];
}];
NEW EDIT:
thanks to amadour, who taught me something with his comments,
i hope he could add an answer of his own, i would vote for him
anyway, to answer to jowie original question:
i got the right animation just moving the contentOffset setting out of the animation block,
and removing UIViewAnimationOptionAllowAnimatedContent (not really needed), and passing pagingScrollView as parameter for transitionWithView
this worked for me:
pagingScrollView.contentOffset = CGPointZero;
[UIView transitionWithView:pagingScrollView duration:3.0 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
// pagingScrollView.contentOffset = CGPointZero; // move up, outside of animation block
} completion:^(BOOL finished) {
NSLog(#"-->> END amimation");
[self refreshPages];
}];

Resources