[英]How to make a view appear through animation when a button is clicked?
我是编码新手。 我正在创建一个应用程序,我需要在单击按钮时显示视图,并且视图应该显示为来自按钮本身。 再次单击该按钮,视图应返回按钮(动画)。
我有像翻转,卷曲的动画,但我不知道如何做到这一点。
这是一个简单的例子。 将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;
}
//这里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];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.