我的iPad项目结构如下: - AppDelegate - MainWindow - 查看控制器 - 查看
View Controllers .m文件以编程方式加载另一个视图并将其放置在屏幕上。这种观点将会滑入和滑出。
我这样做:
- (void)viewDidLoad
{
[super viewDidLoad];
CGRect viewRect = CGRectMake(0, 0, 0, 0);
CalculatorView *v = [[[CalculatorView alloc]
initWithFrame:viewRect] autorelease];
[self.view.window addSubview:v];
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
v.view.frame = CGRectMake(0, 0, 460, 320);
[UIView commitAnimations];
}
我遇到的问题是我在这里添加的子视图似乎没有正确的方向。该项目仅支持景观,并启动到景观。容器视图很好,它包含一些很好的按钮。但是,这个以编程方式加载的视图卡在纵向模式下。我提供了以下自动旋转代码(在加载视图的.m中):
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}
但它永远不会被召唤。
那么,如何在横向和非纵向模式下加载以编程方式添加的子视图? TIA!
答案 0 :(得分:1)
UIView类不接收方向更改消息。
(特别是shouldAutorotateToInterfaceOrientation
方法,这是一个UIViewController方法)
您必须在视图中手动添加方法,以告知方向已更改,您应该在控制器shouldAutorotateToInterfaceOrientation
方法中调用此方法。
为此,您必须在控制器中创建对您的视图的引用,并自己处理内存。
@interface MyController : UIViewController {
CalculatorView *_calculatorView;
}
@end
@implementation MyController
- (void)viewDidLoad
{
[super viewDidLoad];
CGRect viewRect = CGRectMake(0, 0, 0, 0);
//inits _calculatorView without the autorelease. Will be released in the dealloc method
_calculatorView = [[CalculatorView alloc]
initWithFrame:viewRect];
[self.view.window addSubview:v];
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
_calculatorView.view.frame = CGRectMake(0, 0, 460, 320);
[UIView commitAnimations];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
//calls custom interface orientation method
[_calculatorView MyInterfaceChangedCustomMethod:interfaceOrientation];
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}
-(void) dealloc {
[_calculatorView release];
[super dealloc];
}
@end
编辑:如果你的CalculatorView很简单,你需要的是在设备旋转后正确地改变它的框架,我认为最好的方法是使用你的视图的autoresizingMask类似于以下
_calculatorView = [[CalculatorView alloc]
initWithFrame:viewRect];
_calculatorView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;