iOS开发中控制屏幕旋转的编写方法小结

2020-01-14 16:25:01于海丽

复制代码
-(void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration  
{  
    if (UIInterfaceOrientationIsPortrait(toInterfaceOrientation)) {  
        NSLog(@"现在是竖屏");  
        [btn setFrame:CGRectMake(213, 442, 340, 46)];  
    }  
    if (UIInterfaceOrientationIsLandscape(toInterfaceOrientation)) {  
        NSLog(@"现在是横屏");  
        [btn setFrame:CGRectMake(280, 322, 460, 35)];  
    }  
}  
也许,你并不希望用绝对坐标去约束控件,而是希望让它通过旋转自己适应屏幕的旋转
复制代码
- (void)viewDidLoad  
{  
    [super viewDidLoad];  
    // Do any additional setup after loading the view, typically from a nib.  
    UIDevice *device = [UIDevice currentDevice];   
    [device beginGeneratingDeviceOrientationNotifications];  
    //利用 NSNotificationCenter 获得旋转信号 UIDeviceOrientationDidChangeNotification  
    NSNotificationCenter *ncenter = [NSNotificationCenter defaultCenter];   
    [ncenter addObserver:self selector:@selector(orientationChanged) name:UIDeviceOrientationDidChangeNotification object:device];  
}  
  
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation  
{  
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);  
}  
  
-(void)rotation_btn:(float)n  
{  
    UIButton *robtn = self.btn;  
    robtn.transform = CGAffineTransformMakeRotation(n*M_PI/180.0);  
}  
  
-(void)orientationChanged  
{  
    UIDeviceOrientation orientaiton = [[UIDevice currentDevice] orientation];  
      
    switch (orientaiton) {  
        caseUIDeviceOrientationPortrait:               
            [self  rotation_btn:0.0];