屏幕旋转

import "AppDelegate.h"

import "ViewController.h"

@interface AppDelegate ()

@end
@implementation AppDelegate

  • (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];

    ViewController *viewControiller = [[ViewController alloc]init];
    [self.window setRootViewController:viewControiller];

    return YES;
    }


import "ViewController.h"

import "LoginView.h"

@interface ViewController ()

@end

@implementation ViewController

// 是否支持屏幕旋转(默认的是YES)
-(BOOL)shouldAutorotate{
// 如果返回值为YES,支持旋转,返回值为NO,不支持旋转

//  作业:登录界面旋转后重新布局
return YES;

}

// 设置当前界面(viewControler自带的view)所支持的屏幕的方向,系统默认支持竖直,横向向左,横向向右
-(UIInterfaceOrientationMask)supportedInterfaceOrientations{
// 支持所有的屏幕方向
return UIInterfaceOrientationMaskAll;
}

-(void)loadView{
[super loadView];

LoginView *loginView = [[LoginView alloc]init];
self.view = loginView;  

}

import "LoginView.h"

@interface LoginView ()

@property (nonatomic ,retain)UITextField *textField;

@end

@implementation LoginView
-(instancetype)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
[self textField];
}return self;
}
-(UITextField*)textField{
if (!_textField) {

    _textField = [[UITextField alloc]initWithFrame:CGRectMake(80, 100, 100, 40)];

    _textField.backgroundColor = [UIColor redColor];
    [self addSubview:_textField];
}return _textField;

}

// 重写的父类的layoutSubviews,当屏幕旋转的时候,会执行此方法。一般在此方法中对当前view的子视图进行重新布局
-(void)layoutSubviews{
[super layoutSubviews];
// 获取当前屏幕的方向状态
// [UIApplication sharedApplication]:获得当前的应用程序
NSInteger orientation = [UIApplication sharedApplication].statusBarOrientation;
switch (orientation) {

    //  当屏幕方向为水平向左时,我们要将输入框水平居中
    case UIInterfaceOrientationLandscapeLeft:
    {
        CGRect frame = self.textField.frame;
        frame.origin.x = 0;
        self.textField.frame = frame;
    }
        break;
       
        case UIInterfaceOrientationLandscapeRight:
        //  如果是多行执行语句的时候,需要用花括号将他们括起来
    {
        CGRect frame = self.textField.frame;
        frame.origin.x = (CGRectGetWidth(self.frame) - CGRectGetWidth(self.textField.frame))/2;
        self.textField.frame = frame;
    }
        break;
      
    case UIInterfaceOrientationPortrait:{
        CGRect frame = self.textField.frame;
        frame.origin.x = 80;
        self.textField.frame = frame;
    }
        break;
     
    default:
        break;
}

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容