Ios 为以编程方式加载的子视图提供自动旋转支持-iPad
我的iPad项目结构如下: -AppDelegate -主窗口 -视图控制器 --看法 View Controllers.m文件以编程方式加载另一个视图,并将其放置在屏幕上。这个视图将被滑进滑出 我这样做:Ios 为以编程方式加载的子视图提供自动旋转支持-iPad,ios,ipad,landscape-portrait,Ios,Ipad,Landscape Portrait,我的iPad项目结构如下: -AppDelegate -主窗口 -视图控制器 --看法 View Controllers.m文件以编程方式加载另一个视图,并将其放置在屏幕上。这个视图将被滑进滑出 我这样做: - (void)viewDidLoad { [super viewDidLoad]; CGRect viewRect = CGRectMake(0, 0, 0, 0); CalculatorView *v = [[[CalculatorView alloc]
- (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中):
但它从未被呼叫过
那么,如何让以编程方式添加的子视图以横向模式而不是纵向模式加载?
蒂亚 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很简单,并且您只需要在设备旋转后正确更改其帧,那么我认为最好的方法是使用类似于以下内容的you view的autoresizingMask
_calculatorView = [[CalculatorView alloc]
initWithFrame:viewRect];
_calculatorView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
Felipe-现在要尝试这个,我会报告我的发现。Felipe-我想我现在的问题是,“MyInterfaceChangedCustomMethod”应该是什么样子的。通过将其改为UIViewController来解决这个问题怎么样,将UIView作为实例变量?此方法负责更改CalculatorView对象内的视图元素。我刚刚意识到,如果您的CalculatorView不需要以复杂的方式调整其子视图的大小,您可以使用autoresizemask来完成这项工作,而不是使用新方法
_calculatorView = [[CalculatorView alloc]
initWithFrame:viewRect];
_calculatorView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;