1. 程式人生 > >獲取檢視的絕對座標(相對於UIWindow)

獲取檢視的絕對座標(相對於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的絕對座標。