今天遇到了需要获取控件的绝对坐标(即相对屏幕的坐标)。我先试着通过递归获取视图父视图的方法计算绝对坐标,但是在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的绝对坐标。