我制作了一个具有许多UIView子类视图的应用程序。这些视图的大小和方向是随机的,应用程序的屏幕状态可以保存。当用户将屏幕保存在与其打开的设备相同的设备上时,屏幕状态为OK。一切都定位正确。但是,如果用户将屏幕状态保存在iPhone上并从iPad打开,则视图位置不正确。实际上视图看起来更短或更长,中心似乎被正确保存,但视图的旋转和它们的大小(边界属性)不能正常工作。以编程方式将uiviews适用于iPad/iPhone屏幕
这些都是两种方法保存和恢复视图
- (void)encodeWithCoder:(NSCoder *)aCoder {
// Save the screen size of the device that the view was saved on
[aCoder encodeCGSize:self.gameView.bounds.size forKey:@"saveDeviceGameViewSize"];
// ****************
// ALL properties are saved in normalized coords
// ****************
// Save the center of the view
CGPoint normCenter = CGPointMake(self.center.x/self.gameView.bounds.size.width, self.center.y/self.gameView.bounds.size.height);
[aCoder encodeCGPoint:normCenter forKey:@"center"];
// I rely on view bounds NOT frame
CGRect normBounds = CGRectMake(0, 0, self.bounds.size.width/self.gameView.bounds.size.width, self.bounds.size.height/self.gameView.bounds.size.height);
[aCoder encodeCGRect:normBounds forKey:@"bounds"];
// Here I save the transformation of the view, it has ONLY rotation info, not translation or scalings
[aCoder encodeCGAffineTransform:self.transform forKey:@"transform"];
}
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
// Restore the screen size of the device that the view was saved on
saveDeviceGameViewSize = [aDecoder decodeCGSizeForKey:@"saveDeviceGameViewSize"];
// Adjust the view center
CGPoint tmpCenter = [aDecoder decodeCGPointForKey:@"center"];
tmpCenter.x *= self.gameView.bounds.size.width;
tmpCenter.y *= self.gameView.bounds.size.height;
self.center = tmpCenter;
// Restore the transform
self.transform = [aDecoder decodeCGAffineTransformForKey:@"transform"];
// Restore the bounds
CGRect tmpBounds = [aDecoder decodeCGRectForKey:@"bounds"];
CGFloat ratio = self.gameView.bounds.size.height/saveDeviceGameViewSize.height;
tmpBounds.size.width *= (saveDeviceGameViewSize.width * ratio);
tmpBounds.size.height *= self.gameView.bounds.size.height;
self.bounds = tmpBounds;
}
return self;
}
THX您的回复但不幸的是它没有工作做。当视图保存在iPhone上并在iPad上打开时,它的元素在iPad屏幕的x轴上显示得更短。在Y轴上没有问题。当一个视图保存在iPad上并在iPhone上打开时,会发生完全相反的情况。 – Summon 2012-08-10 15:30:41
不客气,但我想解决您的问题:)您是否尝试调试应用程序,并在保存/加载之前和之后检查两个设备上的值?也许这些值可以显示他们有什么问题。 – 2012-08-10 20:18:08
问题的根源在于当视图旋转时,将宽度除以屏幕宽度以正常化其大小是错误的,因为宽度可能等于由于旋转或宽度和高度的组合而造成的高度例如45度旋转。而且,iPad的宽高比与iPhone不同,所以这是另一个需要担心的问题。我希望看到成功处理这些问题的代码。 – Summon 2012-08-11 06:16:33