1 note &
Simplify UIView Animation With Categories
What follows is a category I use to animate UIViews. Adding the animation code where the animation happens feels very messy to me. With these simple categories you can cut down the animation of a UIView in certain situations to a single line of code.
@interface UIView (Extra)
// Animate removing a view from its parent
- (void) removeWithTransition:(UIViewAnimationTransition) transition andDuration:(float) duration;
// Animate adding a subview
- (void) addSubview:(UIView *)view withTransition:(UIViewAnimationTransition) transition withDuration:(float) duration;
// Animate the changing of a views frame
- (void) setFrame:(CGRect) fr withDuration:(float) duration;
// Animate changing the alpha of a view
- (void) setAlpha:(float) a withDuration:(float) duration;
@end
@implementation UIView (Extra)
- (void) removeWithTransition:(UIViewAnimationTransition) transition andDuration:(float) duration
{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:duration];
[UIView setAnimationTransition:transition forView:self.superview cache:YES];
[self removeFromSuperview];
[UIView commitAnimations];
}
- (void) addSubview:(UIView *)view withTransition:(UIViewAnimationTransition) transition withDuration:(float) duration
{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:duration];
[UIView setAnimationTransition:transition forView:self cache:YES];
[self addSubview:view];
[UIView commitAnimations];
}
- (void) setFrame:(CGRect) fr withDuration:(float) duration
{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:duration];
self.frame = fr;
[UIView commitAnimations];
}
- (void) setAlpha:(float) a withDuration:(float) duration
{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:duration];
self.alpha = a;
[UIView commitAnimations];
}
@end
Here is an example of using the setFrame:withDuration: to slide a UIDatePicker on and off screen.
- (void) hideDatePicker:(BOOL) hide
{
CGRect hideFrame = CGRectMake(0, self.view.frame.size.height, datePicker.frame.size.width, datePicker.frame.size.height);
CGRect showFrame = CGRectMake(0, self.view.frame.size.height - datePicker.frame.size.height, datePicker.frame.size.width, datePicker.frame.size.height);
if(!hide) [datePicker setFrame:showFrame withDuration:.5];
else [datePicker setFrame:hideFrame withDuration:.5];
}
The following is an example of the flip animation used in a default “utility” application.
// Show the view with animation [self.view addSubview:myviewcontroller.view withTransition:UIViewAnimationTransitionFlipFromLeft withDuration:.5]; // Remove the view with animation [myviewcontroller.view removeWithTransition:UIViewAnimationTransitionFlipFromLeft andDuration:.5];
To summarize, categories rock! They make it easy to add functionality to existing classes without the need to subclass. As always questions and comments are welcome.



