【问题标题】:Get a UIView’s bounds relative to the window?获取 UIView 相对于窗口的边界?
【发布时间】:2014-01-20 14:22:22
【问题描述】:

我在UIView 中有几个UIButton 实例,而这些实例又位于应用程序的主UIView 中。我想要得到的是按钮框架之一的CGRect,相对于窗口。

因此,例如,如果我的内部视图相对于主视图位于50, 50,那么按钮位于其中的10, 10,我想返回60, 60

有没有一种简单的方法可以做到这一点,而不必跟踪父视图并将它们相加等?

【问题讨论】:

  • - (CGRect)convertRect:(CGRect)rect toView:(UIView *)view; - (CGRect)convertRect:(CGRect)rect fromView:(UIView *)view;
  • 谢谢,你能给我一个粗略的例子来说明我将如何使用它吗?

标签: ios objective-c uiview bounds cgrect


【解决方案1】:

您可以使用-[UIView convertRect:toView]-[UIView convertRect:fromView:] 将矩形转换为不同视图的坐标系。

所以,如果您有对最外层视图的引用(也许如果您使用导航控制器,那可能是最外层视图):

UIView *outerView = self.navigationController.view;
UIView *innerView = self.myButton;

CGRect buttonRect = [self.view convertRect:self.innerView.frame toView:outerView];

还有等效的convertPoint: 方法。然后,实际上只是确定要从/转换到哪些视图。

【讨论】:

  • 这给了我一些非常奇怪的结果。有问题的按钮在其超级视图中位于{162, 0},而该超级视图在主视图中位于{0, 355}。然而,它给了我{324, 291} 作为convertRect 的输出。为什么会这样?
  • 嗯,这很奇怪。你确定你将正确的超级视图传递给convertRect/convertPoint
  • 据我所知,是的。是按钮,在按钮视图里面,在主视图里面,我打电话给CGPoint centerOfButtonInSuperview = [button convertPoint:button.center toView:self.view];
  • 出于兴趣,如果您使用button.origin 而不是button.center 会发生什么?
【解决方案2】:
UIView *parent = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 50, 50)];
UIView *child = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 10, 10)];
[parent addSubview:child];
[self.view addSubview:parent];
NSLog(NSStringFromCGRect([self.view convertRect:child.frame fromView:child.superview]));

日志中的结果:

{{60, 60}, {10, 10}}

【讨论】:

    【解决方案3】:

    使用下面的函数。

    - (CGPoint)convertPoint:(CGPoint)point toView:(UIView *)view;
    
    CGPoint pt = [button convertPoint:CGPointMake(button.frame.origin.x, button.frame.origin.y) toView:yourWindow];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-17
      • 2011-03-17
      • 1970-01-01
      • 2014-08-10
      • 2021-01-03
      • 1970-01-01
      • 1970-01-01
      • 2011-04-12
      相关资源
      最近更新 更多