iOS最小化视图和左上角的所有子视图

时间:2014-05-28 07:57:18

标签: ios uiview uiviewanimation

我有一个UIView,其中包含一些子视图(以及其中的一些子视图)。我试图将整个视图最小化到屏幕的左上角,直到它达到一定的大小(20 x 20),但我很难做到这一点。

我首先尝试[UIView beginAnimations:nil context:nil];,但这并没有调整子视图的大小。此外,由于填充和其他子视图的数量,将每个子视图帧设置为一些新的大小并使其全部运行良好将非常困难。

然后我尝试了这段代码:

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:2.0f];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];

[self.myCardsCarousel.layer setAnchorPoint:CGPointMake(0.0f, 0.0f)];
[self.myCardsCarousel setTransform:CGAffineTransformMakeScale(0.0f, 0.0f)];

CGRect addCardsButtonFrame = self.addCardsButton.frame;
addCardsButtonFrame.size.height = 0.0f;

[self.addCardsButton setFrame:addCardsButtonFrame];

[UIView commitAnimations];

但这并没有最小化到屏幕的左上角。相反,它最小化到屏幕的死点。

如何将其固定在屏幕的左上角?另外,当视图达到一定大小时,如何停止CGAffineTransformMakeScale()

1 个答案:

答案 0 :(得分:0)

一种可能的解决方案是创建视图的快照,并将快照设置为角落的动画(假设最小化视图可以是静态的)。事件的一般顺序是

  • 将父视图的快照创建为内存位图
  • 从快照
  • 创建UIImageView
  • 将UIImageView放在父视图前面
  • 使用其hidden属性
  • 隐藏父视图
  • 将UIImageView设置为角落

恢复视图

  • 将UIImageView动画回原始位置
  • 取消隐藏父视图
  • 删除UIImageView并将其丢弃

首先,您需要UIImageView的属性

@property (strong, nonatomic) UIImageView *snapshotView;

这里是最小化视图的代码

// create a snapshot image of the parent view
UIGraphicsBeginImageContextWithOptions( self.parentView.bounds.size, YES, 0 );
CGContextRef context = UIGraphicsGetCurrentContext();
[self.parentView.layer renderInContext:context];
UIImage *snapshot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

// create a UIImageView from the snapshot
self.snapshotView = [[UIImageView alloc] initWithFrame:self.parentView.frame];
self.snapshotView.image = snapshot;
[self.view addSubview:self.snapshotView];

// hide the parent view in place, while animating the snapshot view into the corner
self.parentView.hidden = YES;
[UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveEaseInOut
animations:^
{
     self.snapshotView.frame = CGRectMake( 0, 0, 20, 20 );
}
completion:nil];

这是恢复视图的代码

[UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveEaseInOut
animations:^
{
    // animate the snapshot view back to original size
    self.snapshotView.frame = self.parentView.frame;
}
completion:^(BOOL finished)
{
    // reveal the parent view and discard the snapshot view
    self.parentView.hidden = NO;
    [self.snapshotView removeFromSuperview];
    self.snapshotView = nil;
}];