如何将一个视图从一个容器视图中移到另一个容器视图中?

3
我有一个主视图。 在主视图中有两个容器视图:按钮容器和显示容器。 在这些容器的每个容器中分别有按钮和显示字段。
简而言之,我有三个层次的视图:主视图、子(容器)和子子(按钮和字段)。
当按下按钮时,我想要从按钮区域动画地移动该按钮的图像到显示区域。也就是说,我需要将它向上移动两个级别,然后再向下移动两个级别。
目前,我正在创建一个UIImage,在按钮上方与自定义按钮的UIImage相同。我将其移动,然后在动画结束时销毁它,这样我就不必修改实际按钮(我希望它保持原位,以便可以重新使用它)。
显然,我可以获得此UIImageView的中心/边界/帧。
但是,我很难确定目标的坐标。 Frame和Center是相对于父视图的,但这只是向上一级。似乎需要进行大量的数学计算才能加起来正确的X和Y偏移量以到达目的地。
这是UIView的convertRect:toView:或convertRect:fromView:的工作吗? 我很难确定如何使用它们,或者决定它们是否实际上是要使用的正确方法。
看起来是一个常见的问题——将某些东西从一个“嵌套”视图移动到另一个“嵌套”视图——但我已经搜索了一下,找不到答案。

convertRect:...绝对是用于此操作的正确方法。 - MusiGenesis
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];
}];

几乎成功了 - 必须进行一次修改:由于subB不在容器视图中,也就是说,它是视图控制器视图的子视图(self),因此我不认为需要将endLocalFrame转换为convertRect。由于subB的框架已经在主视图的坐标系统中,只需从subB获取框架并对其执行动画即可 - 如myButton.frame = subB.frame;} - 对吗?这非常有帮助,现在它已经成功运行,谢谢。 - andrewmobile
那会改变按钮框架以覆盖 subB。我认为 subB 是一个更大的区域,而您想要将按钮放在其中。 - danh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接