【问题标题】:iOS convertPoint:toView: return inconsistent valuesiOS convertPoint:toView: 返回不一致的值
【发布时间】:2014-05-05 08:21:41
【问题描述】:

我正在尝试获取 viewController 的视图相对于屏幕顶部的偏移量。

我认为我可以将视图的原点转换为窗口的坐标,所以我在我的 viewControllers 中尝试了类似的操作:

CGPoint basePoint = [self.view convertPoint:self.view.frame.origin toView:nil];
CGFloat offset = basePoint.y;

在某些情况下它会按预期工作,但在其他情况下,即使参数相同,它也会返回不同的值。

关于这个 convertPoint:toView: 幕后发生的事情的任何想法:可能会导致不同的返回值?

或者,如果您有任何其他建议来获取我的 viewController 的视图相对于屏幕顶部的偏移量,我们将不胜感激!

谢谢

【问题讨论】:

  • 窗口不旋转,其他视图旋转。
  • 也永远不要假设原点是 0。

标签: ios objective-c uiwindow


【解决方案1】:

您正在将您的point 转换为nil 视图中的一个点。

最初的window,有一个rootViewController,它有一个view,所以你可以访问那个视图:

UIView *firstView = [[[(YourClassAppDelegate *)[UIApplication sharedApplication] window] rootViewController] view];

CGPoint basePoint = [self.view convertPoint:self.view.frame.origin toView:firstView];
CGFloat offset = basePoint.y;

记得在实现中导入你的应用代理类。

【讨论】:

  • 非常感谢,但这没有用。它的行为仍然不一致。并且来自 Apple 文档:如果 view 为 nil,则此方法会转换为窗口基坐标。
【解决方案2】:

我最终爬上了超级视图链并将每个视图的所有 offsets.y 加起来。不确定这是否是最好的方法,尤其是在性能方面,但目前它有效。

UIView *view = self.view;
CGFloat offset = view.frame.origin.y;

while (view.superview != nil) {
    offset += view.superview.frame.origin.y;
    view = view.superview;
}

【讨论】:

    【解决方案3】:

    尝试改变这个

    CGPoint basePoint = [self.view convertPoint:self.view.frame.origin toView:nil];
    

    CGPoint basePoint = [self.view.superview convertPoint:self.view.frame.origin toView:nil];
    

    【讨论】:

    • 我想你的意思是 self.view.superview 因为它是一个 viewController。它确实表现得更加一致,但是在一些显然有一些转换集的视图中,它仍然给出了意想不到的结果。
    • 呃……有什么看法?
    【解决方案4】:

    你的两个视图必须有共同的父视图(例如UIWindow),否则你会得到奇怪的结果。

    当您尝试将-viewDidLoad 中的UIViewController 的视图与convertPoint 一起使用时,可能会发生这种情况,因为视图尚未添加到视图层次结构中。

    - (void)viewDidLoad
    {
        [super viewDidLoad];
    
        NSLog(@"%@", self.view.superview); // nil, not added to view hierachy
    
        // If you try to convert point using self.view (or any self.view subview), 
        // and any other view, which is not self.view subview (for example, UIWindow),
        // it will fail, because self.view is not yet added to the view hierachy.
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-29
      • 2019-01-28
      • 1970-01-01
      • 2023-02-08
      • 1970-01-01
      • 2016-01-27
      • 2016-02-27
      相关资源
      最近更新 更多