我是编码新手。我正在制作一个应用程序,我需要在单击按钮时显示一个视图,并且该视图应该看起来好像它来自按钮本身。再次单击按钮时,视图应返回按钮(动画)。
我有翻转、卷曲等动画,但我不知道该怎么做。
这是一个简单的例子。设置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];
}
}];
}
然后创建一个布尔属性来指示是否显示视图,并为该属性实现一个自定义设置器。
@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];