动画伸缩显示视图的简单示例

来源:互联网 发布:中兴java面试题 编辑:程序博客网 时间:2024/05/21 14:05
 

动画伸缩显示视图的简单示例

业务需要这样一种效果,iPad上要能在Detail视图中动画效果显示提示信息。效果类似这样(见蓝色部分视图及旁边的按钮):

image

点击按钮后,蓝色视图及包含的子视图收缩直至消失:

imageimage

动画的原理是:

  • 蓝色视图及子视图,在点击按钮后宽度设置为0
  • 使用动画效果(UIViewAnimationCurveEaseInOut),并延时一段时间

写了个类来封装这个动画效果,只需传入参数:蓝色视图和按钮对象引用即可。

封装类的interface部分:

#import <Foundation/Foundation.h>

@interface AnimationHelper : NSObject {
    NSMutableArray *subviews;
    int viewX;
    int viewWidth;
}

-(AnimationHelper *)init: (UIView *)parentView;

-(void)doOnClick:(UIView *) v:(UIButton *) b;

@end

实现类部分:

#import "AnimationHelper.h"

@implementation AnimationHelper

-(AnimationHelper *)init: (UIView *)parentView{
    subviews=[[NSMutableArray alloc] initWithCapacity:0];
   
    for (UIView *v in parentView.subviews) {
        [subviews addObject:[NSNumber numberWithInt:[v frame].size.width]];
    }
   
    viewX=[parentView frame].origin.x;
    viewWidth=[parentView frame].size.width;
   
    return self;
}

-(void)doOnClick:(UIView *) v: (UIButton *) b{
    CGContextRef context = UIGraphicsGetCurrentContext();
    [UIView beginAnimations:@"Curl" context:context];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:0.5];
    CGRect rect = [v frame];
    CGRect rect1=[b frame];
    BOOL flag=rect.size.width>0;
   
    if (flag) {
        rect1.origin.x=(viewX+viewWidth)- rect.size.width;
        rect.size.width=0;
        v.alpha=0.0f;
    }else {
        rect.size.width=viewWidth;
        rect1.origin.x=(viewX+viewWidth);
        v.alpha=1.0f;
    }
   
   
    if (flag) {
        for (UIView * mv in v.subviews) {
            NSLog(@"<—subviews.");
            CGRect r=[mv frame];
            r.size.width=0;
            mv.alpha=0.0f;
            [mv setFrame:r];
        }
    }else {
        for (int i=0;i<[v.subviews count];i++) {
            NSLog(@"–>subviews.");
            UIView *mv=[v.subviews objectAtIndex:i];
            CGRect r=[mv frame];
            r.size.width=[[subviews objectAtIndex:i] intValue];
            mv.alpha=1.0f;
            [mv setFrame:r];
        }
    }
    [b setFrame:rect1];
    [v setFrame:rect];
   
    [UIView commitAnimations];
   
}

@end

在DetailViewController中的调用该类,需要在加载视图后实例化AnimationHelper:

- (void)viewDidLoad {
    helper=[[AnimationHelper alloc] init:changeView];
    [super viewDidLoad];
}

 

然后,就是点击按钮的方法部分:

-(IBAction)onClickButton:(id)sender{
    [helper doOnClick:changeView :button];
}

DetailViewController interface用到的部分的代码片段:

    UIButton *button;
    UIView *changeView;
   
    UILabel *myLabel;
   
    AnimationHelper *helper;
}

原创粉丝点击