我创建了一个新项目作为单视图应用程序。在视图控制器中添加了用于将视图坐标转换为窗口坐标的代码:
- (void) dumpFrame
{
CGRect bounds = self.view.bounds;
// UIView* rootView = [UIApplication sharedApplication].keyWindow.rootViewController.view;
// I tried rootView instead of nil and self.view.superview instead of self.view but got {0,0} coordinate
CGPoint newCoord = [self.view convertPoint: bounds.origin
toView: nil];
bounds.origin.x = newCoord.x;
bounds.origin.y = newCoord.y;
NSLog(@"view.frame=%@", NSStringFromCGRect(bounds));
}
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
[super didRotateFromInterfaceOrientation: fromInterfaceOrientation];
NSLog(@"===>didRotate");
[self dumpFrame];
}
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
[super willRotateToInterfaceOrientation: toInterfaceOrientation duration: duration];
NSLog(@"===>willRotate");
[self dumpFrame];
}
我的日志:
===>wilRotate
view.frame={{0, 20}, {768, 1004}}
===>didRotate
view.frame={{748, 0}, {1024, 748}}
而不是
{{0, 20}, {1024, 748}}
我得到了
{{748, 0}, {1024, 748}}
旋转后获取{0,20}需要做什么?我会很高兴任何帮助。
答案 0 :(得分:3)
显然UIWindow
的坐标系始终保持纵向,只需设置transform
根VC的UIWindow
属性即可应用旋转。从this SO question获得此信息。
至少这可以解释为什么你会得到意想不到的坐标。不幸的是,我一直无法找到如何实际解决问题的方法。我假设应该有一种方法来利用有效的转换矩阵,但我的数学技能不符合这一点。也许其他人可以介入这里。
修改
也许你可以用this code做一些事情(在“iOS Developer's Cookbook”的GitHub回购中)。部分代码将在this article中解释并显示插图。
答案 1 :(得分:-1)
尝试:
CGPoint newCoord = [view.superview convertPoint: bounds.origin
toView: nil];
视图的原点是相对于它的超视图,所以你必须从超视图坐标系转换点