3

我有一个主要观点。主视图内部有两个容器视图:按钮容器和显示容器。每个容器内部分别是按钮和显示字段。

简而言之,我有三个级别的视图:主视图、子视图(容器)和子子视图(按钮和字段)。

当按下按钮时,我想将该按钮的图像从按钮区域动画到显示区域。也就是说,我需要将它向上移动两层,然后再向下移动两层。

目前,我正在按钮顶部创建一个与自定义按钮的 UIImage 相同的 UIImage。我移动它,然后在动画结束时将其销毁,因此我不必更改实际按钮(我想将其保留在原位以便重复使用它)。

显然我可以得到这个 UIImageView 的中心/边界/框架。

但是,我无法确定目的地的坐标。Frame 和 Center 是相对于 superview 的,但这只是上一层。似乎需要做很多数学运算才能将正确的 X 和 Y 偏移量相加才能到达目的地。

这是 UIView 的 convertRect:toView: 或 convertRect:fromView: 的工作吗?我很难确定如何使用它们,或者确定它们是否真的是正确的使用方法。

似乎是一个很常见的问题——将某些东西从一个“嵌套”视图移动到另一个“嵌套”视图——但我已经搜索过但找不到答案。

4

1 回答 1

0

那些 convertRect 方法很难掌握。您的视图包含两个子视图 subA 和 subB,并且 subA 包含一个按钮,并且您希望为从 subA 移动到 subB 的按钮设置动画。让我们在具有主视图的视图控制器中制作动画......

// subA is the receiver.  that's the coordinate system we care about to start
CGRect startFrame = [subA convertRect:myButton.frame toView:self.view];

// this is the frame in terms of subB, where we want the button to land
CGRect endFrameLocal = CGRectMake(10,10,70,30);
// convert it, just like the start frame
CGRect endFrame = [subB convertRect:endFrameLocal toView:self.view]; 

// this places the button in the identical location as a subview of the main view
// changing the button's parent implicitly removes it from subA
myButton.frame = startFrame;
[self.view addSubview:myButton];

// now we can animate in the view controller's view coordinates
[UIView animateWithDuration:1.0 animations:^{
    myButton.frame = endFrame;  // this frame in terms of self.view
} completion^(BOOL finished) {
    myButton.frame = endFrameLocal;  // this frame in terms of subB
    [subB addSubview:myButton];
}];
于 2012-06-26T04:37:57.437 回答