1.新建工程名为RotateDemo , File->New->Project ->single View Application -> next
2.在view视图上添加两个Label,
// RotateViewController.h
#import <UIKit/UIKit.h>
@interface RotateViewController : UIViewController
{
UILabel *upLabel;
UILabel *downLabel;
CGRect upFrame;
CGRect dowmFrame;
}
@end
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
upFrame = CGRectMake(10, 10, 300, 100);
dowmFrame = CGRectMake(10, 350, 300, 100);
// 初始化Label
upLabel = [[UILabel alloc] initWithFrame:upFrame];
downLabel = [[UILabel alloc] initWithFrame:dowmFrame];
// 设置标题
[upLabel setText:@"在上面"];
[downLabel setText:@"在下面"];
// 设置字体大小
upLabel.font = [UIFont systemFontOfSize:48.0];
downLabel.font = [UIFont systemFontOfSize:48.0];
// 字体加粗
upLabel.font = [UIFont boldSystemFontOfSize:48];
downLabel.font = [UIFont boldSystemFontOfSize:48];
// 如果label标题很长,可以使用此方法让标题大小自动适合label宽度
/*
upLabel.adjustsFontSizeToFitWidth =YES;
downLabel.adjustsFontSizeToFitWidth = YES;
*/
// 设置Label标题居中对其
upLabel.textAlignment=UITextAlignmentCenter;
downLabel.textAlignment = UITextAlignmentCenter;
// 设置label标题颜色
[upLabel setTextColor:[UIColor blackColor]];
[downLabel setTextColor:[UIColor blueColor]];
// 设置Label透明度0是完全透明,1是不透明
upLabel.alpha = 0.9;
downLabel.alpha = 0.4;
// 把label添加到视图上
[self.view addSubview:upLabel];
[self.view addSubview:downLabel];
}
⌘「Command 键」+ -> 可以切换视图旋转方向,或者菜单栏点击硬件,在下拉菜单里有旋转方向控制选项,运行结果截图




出现这情况是iphone根据重力感应所产生的,view视图发生改变,但是两个label坐标并未改变,所以在下面那个label并未显示出来,还有个就是当Home方向向上的时候,和第二中情况一样了,label坐标发生变化了,这是针对iphone的特殊情况,当有电话呼入的时候,如果Home键在上,那么我们的话筒和听筒就反了,主要调用的是这个实例方法
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
他的意思就是不支持Home键在上方,如果是ipad我们只需return YES;意思支持屏幕任何方向的旋转,
ios设置了四个方向变量
UIInterfaceOrientationPortrait//正常情况下的竖屏
UIInterfaceOrientationPortraitUpsideDown//Home键在上
UIInterfaceOrientationLandscapeLeft//Home键在左
UIInterfaceOrientationLandscapeRight//Home键在右
3.重写willAnimateRotationToInterfaceOrientation方法,重新设置控件的大小与位置
- (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
if (UIInterfaceOrientationIsPortrait(toInterfaceOrientation)) {
upLabel.frame = upFrame;
downLabel.frame = dowmFrame;
}
else {
upLabel.frame = CGRectMake(90, 10, 300, 100);
downLabel.frame = CGRectMake(90, 190, 300, 100);
}
}
当屏幕出现旋转开始并在动画发生之前自动调用此方法,首先if判断屏幕方向是竖着(
UIInterfaceOrientationIsPortrait)的还是横着(
UIInterfaceOrientationIsLandscape),toInterfaceOrientation是传入参数,从变量命名意思我们就可以看出是界面方向,此方法是对label进行屏幕不同方向的重新布局,