UIView からサブクラス化された多くのビューを持つアプリを作成します。これらのビューのサイズと向きはランダムで、アプリの画面の状態を保存できます。ユーザーが画面を開いたのと同じデバイスに画面を保存すると、画面の状態は OK になります。すべてが正しく配置されています。ただし、ユーザーが画面の状態を iPhone に保存し、iPad から開いた場合、ビューは正しく配置されません。実際には、ビューは短くまたは長く表示され、中心は正しく保存されているように見えますが、ビューの回転とそのサイズ (境界プロパティ) は正常に機能していません。
これらは、ビューの状態を保存および復元する 2 つの方法です。
- (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;
}