Iphone 如何将视图从一个容器视图内部移动到另一个容器视图内部?

Iphone 如何将视图从一个容器视图内部移动到另一个容器视图内部?,iphone,ios,uiview,nested,coordinates,Iphone,Ios,Uiview,Nested,Coordinates,我有一个主视图。 主视图内部有两个容器视图:按钮容器和显示容器。 每个容器中分别有按钮和显示字段 简而言之,我有三个级别的视图:主视图、子视图(容器)和子视图(按钮和字段) 当按下一个按钮时,我想将该按钮的图像从按钮区域动画到显示区域。也就是说,我需要向上移动两层,然后再向下移动两层 目前,我正在按钮顶部创建一个UIImage,与自定义按钮的UIImage相同。我移动它,然后在动画结束时销毁它,这样我就不必更改实际的按钮(我希望它保持在原位,以便可以重复使用) 显然,我可以得到这个UIImage

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

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

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

目前,我正在按钮顶部创建一个UIImage,与自定义按钮的UIImage相同。我移动它,然后在动画结束时销毁它,这样我就不必更改实际的按钮(我希望它保持在原位,以便可以重复使用)

显然,我可以得到这个UIImageView的中心/边界/帧

但是,我很难确定目的地的坐标。“帧”和“中心”是相对于“超级视图”的,但这只是向上一层。似乎有很多数学要做,以加上正确的X和Y偏移量到达目的地

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


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

那些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];
}];

convertRect:。。。这些方法绝对是正确的。几乎成功了-不得不做一个更改:因为subB不在容器视图中,也就是说,它是视图控制器视图(self)的子视图,所以我认为没有必要转换endLocalFrame。因为subB的帧已经在主视图的坐标系中,所以只需从subB抓取帧并执行动画即可-如myButton.frame=subB.frame;}-对吗?这是一个很大的帮助,它现在工作得很好,谢谢你。这将改变按钮框架,以涵盖subB。我认为subB是一个更大的区域,您希望按钮放在其中。