单击按钮时如何通过动画显示视图?

时间:2012-05-28 12:11:33

标签: iphone ios

我是编码新手。我正在创建一个应用程序,我需要在单击按钮时显示视图,并且视图应该显示为来自按钮本身。再次单击该按钮,视图应返回按钮(动画)。

我有像翻转,卷曲的动画,但我不知道该怎么做。

2 个答案:

答案 0 :(得分:6)

这是一个简单的例子。将showView:设置为按钮的操作。

- (IBAction)showView:(UIButton *)sender {
    // Create a view with the size and position of the tapped button
    UIView *view = [[UIView alloc] initWithFrame:sender.frame];
    // Set a color on the view
    view.backgroundColor = [UIColor redColor];
    // Add the new view to the main view. The new view will be displayed over any other views
    [self.view addSubview:view];
    // Animate the change of the new view's frame. We use the bounds of the main view.
    [UIView animateWithDuration:3.6 animations:^{
        view.frame = self.view.bounds;
    }];
}

完整解决方案:

首先为视图和按钮创建属性。你如何初始化这些取决于你。

@property (strong, nonatomic) UIButton *button;
@property (strong, nonatomic) UIView *aView;
...
@synthesize button = _button;
@synthesize aView = _aView;

然后创建一个方法,在两个帧之间设置动画视图,如果要求,将在动画结束时从其超级视图中删除视图。

- (void)animateView:(UIView *)view 
           fromRect:(CGRect)from 
             toRect:(CGRect)to 
       inParentView:(UIView *)parent 
     removeWhenDone:(BOOL)remove 
{
    if (!remove) {
        [parent addSubview:view];
    }
    view.frame = from;
    [UIView animateWithDuration:3.6 animations:^{
        view.frame = to;
    } completion:^(BOOL finished) {
        if (remove) {
            [view removeFromSuperview];
        }
    }];
}

然后创建一个布尔属性,指示是否显示视图,并为该属性实现自定义setter。

@property (assign, nonatomic) BOOL viewShown;
...
@synthesize viewShown = _viewShown;

- (void)setViewShown:(BOOL)viewShown
{
    _viewShown = viewShown;
    if (_viewShown) {
        // Insert your own toRect
        [self animateView:self.aView fromRect:self.button.frame toRect:CGRectMake(0, 0, 100, 100) inParentView:self.view removeWhenDone:NO];
    } else {
        [self animateView:self.aView fromRect:self.aView.frame toRect:self.button.frame inParentView:self.view removeWhenDone:YES];
    }
}

最后,在按钮的操作中,您可以翻转viewShown属性。

- (IBAction)showView:(UIButton *)sender {
    self.viewShown = !self.viewShown;
}

答案 1 :(得分:-2)

//这里animationButton是按钮的名称 //这里aView是一个视图

aView.view.center = animationButton.center;

现在,将视图缩放到如图所示的小范围,这样当你制作它时,它就会显示为来自按钮本身。

CGAffineTransform trans = CGAffineTransformScale(aView.view.transform, 0.01, 0.01);

aView.view.transform = trans;   // do it instantly, no animation

[self.view addSubview:aView.view];

// now return the view to normal dimension, animating this transformation

//现在借助动画,可以通过动画

在很大程度上缩放视图
[UIView animateWithDuration:2.0 delay:0.0 options:UIViewAnimationCurveEaseInOut
                 animations:^{
                                  aView.view.transform =   CGAffineTransformScale(aView.view.transform, 70.0, 70.0);
                 }
                 completion:nil];
相关问题