Convert a UIView origin point to its Window coordi

2019-01-22 18:04发布

I want to get the origin of scrollView in the window coordinate system. For Example, presently, scollView origin is (0,51). But in window coordinate system it should be 51 + 44(navigation bar height)+20(status bar height) = 115. Means in window coordinate system the scrollView.frame.origin should be (0,115). I tried with convertPoint: methods but getting (0,51) or (0,0) sometimes. Please provide a solution to this. Thanks

4条回答
相关推荐>>
2楼-- · 2019-01-22 18:30

Note that these functions will only work after view controller finished laying out subviews. So if you want that when view loads, you can use viewDidLayoutSubviews / viewDidAppear, but not in viewDidLoad / viewWillAppear etc...

This code worked for me:

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];

    CGPoint originInSuperview = [self.view.superview convertPoint:CGPointZero fromView:self.scrollView];
}
查看更多
该账号已被封号
3楼-- · 2019-01-22 18:41

I tried with TechZen solution but to no avail. Instead of converting scrollView's origin,I referred to apple docs UIWindow class Reference and converted the endCenter of the keyboard to my view's coordinate system by using this code [self.view convertPoint:endCentre fromView:[UIApplication sharedApplication].keyWindow]. This piece of code worked and hence solved my problem. However, the question still remains as to why it does not gives the proper coordinate of scrollView.origin.So, basically I got a workaround by converting keyboard endcenter instead of scrollView.origin. Oh, and I was doing all this stuff in order to calculate my scrollView's new height when keyboard appears on screen. So, if somebody has a solution to this problem or any better solution, Please let all of us know.

查看更多
Deceive 欺骗
4楼-- · 2019-01-22 18:48

It sounds like your not converting between the proper views. A view's frame is set to the coordinates of it's superview, not its own internal coordinates, so if you were trying to convert the origin of a view to window coordinates, you would need to use the superview:

[[self superview] convertPoint:self.frame.origin toView:theWindow];

However, it is even simpler to convert the zero point from the view itself to the window. The two pieces of code are equivalent, and so it isn't necessary to use the origin at all.

[self convertPoint:CGPointZero toView:theWindow];
查看更多
Root(大扎)
5楼-- · 2019-01-22 18:49

Swift 2.1:

In viewDidAppear(otherwise elements are not yet layered) of your ViewController:

        var yourFrame = yourScrollView.convertRect(yourScrollView.frame, toView: self.view)

        //PRINT THE WHOLE RECT
        print(yourFrame)

        //PRINT A DETAILED VERSION OF THE FRAME, ALSO CAN PERFORM CALCULATION BETWEEN THE RECT PARAMETERS TO GET , FOR EXAMPLE, WIDTH POINT IN THE SUPERVIEW:
        print("X: \(yourFrame.origin.x) Y: \(yourFrame.origin.y) WIDTH: \(yourFrame.width) HEIGHT: \(yourFrame.height)")
查看更多
登录 后发表回答