【问题标题】:How to move view from inside a container view to inside another container view?如何将视图从容器视图内部移动到另一个容器视图内部?
【发布时间】:2012-06-27 08:35:21
【问题描述】:

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

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

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

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

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

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

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

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

【问题讨论】:

  • convertRect:... 绝对是正确的方法。

标签: iphone ios uiview nested coordinates


【解决方案1】:

那些 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 不在容器视图内,也就是说,它是视图控制器视图(自身)的子视图,所以我认为不需要convertRect'ing endLocalFrame。由于 subB 的框架已经在主视图的坐标系中,只需从 subB 抓取框架并对其执行动画 - 如 myButton.frame = subB.frame;} - 对吗?这是一个很大的帮助,现在运行良好,谢谢。
  • 这将更改按钮框架以覆盖 subB。我认为 subB 是一个更大的区域,您希望将按钮放置在其中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-11
  • 1970-01-01
  • 2014-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多