獲取視圖的絕對座標(相對於UIWindow)

今天遇到了需要獲取控件的絕對座標(即相對屏幕的座標)。我先試着通過遞歸獲取視圖父視圖的方法計算絕對座標,但是在tableViewCell上就總是不準,也沒搞懂哪裏出了問題,於是就果斷放棄。百度谷歌了有一會兒才搞出來正確的,在這裏整理一下。

        UIWindow *window;
        id<UIApplicationDelegate> delegate = [[UIApplication sharedApplication] delegate];
        if ([delegate respondsToSelector:@selector(window)]) {
            window = [delegate performSelector:@selector(window)];
        } else {
            window = [[UIApplication sharedApplication] keyWindow];
        } 
        CGPoint point = [window convertPoint:CGPointMake(0, 0) toView:currentView];

代碼中得到的point就是視圖currentView的絕對座標。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章