iOS convertPoint:toView:返回不一致的值

时间:2014-05-05 08:21:41

标签: ios objective-c uiwindow

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

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

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

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

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

或者,如果您有任何其他建议来获取我的viewControllers视图相对于屏幕顶部的偏移量,那将非常感谢!

由于

4 个答案:

答案 0 :(得分:0)

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

最初的windowrootViewController有一个view,因此您可以访问该视图:

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

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

记得在实现中导入你的app delegate类。

答案 1 :(得分:0)

尝试更改此

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

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

答案 2 :(得分:0)

我最终爬上超级视图链并将每个视图中的所有偏移量相加。不确定它是否是最佳方法,尤其是性能方面,但现在它可行。

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

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

答案 3 :(得分:0)

您的两个观点必须具有共同的超级视图(例如UIWindow),否则您将获得奇怪的结果。

当您尝试在UIViewController-viewDidLoad使用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.

}