这是一个简单的例子。放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;
}