点击button时如何通过animation显示视图?

我是新来的编码。 我正在做一个应用程序,我需要使一个视图出现,当一个button被点击,视图应该出现,就好像它已经从button本身。 再次点击button,视图应该返回到button(animation)。

我有像翻转,curl的animation,但我不知道如何做到这一点。

这是一个简单的例子。 设置showView:作为button的动作。

 - (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; }]; } 

完整解决scheme

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

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

然后创build一个animation两帧之间的视图的方法,如果要求,将在animation结束时从其超视图中移除视图。

 - (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]; } }]; } 

然后创build一个布尔属性,指示是否显示视图,并为属性实现自定义设置器。

 @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]; } } 

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

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

//这里animationButton是button的名字//这里aView是一个视图

aView.view.center = animationButton.center;

现在,如图所示,将视图缩小到一个小的范围,这样当你把它围起来的时候,就会显示出来,就好像它是从button本身来的。

 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 

//现在借助animation,通过animation在很大程度上缩放视图

 [UIView animateWithDuration:2.0 delay:0.0 options:UIViewAnimationCurveEaseInOut animations:^{ aView.view.transform = CGAffineTransformScale(aView.view.transform, 70.0, 70.0); } completion:nil];