今天遇到了需要獲取控件的絕對座標(即相對屏幕的座標)。我先試着通過遞歸獲取視圖父視圖的方法計算絕對座標,但是在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的絕對座標。