使用通知监听屏幕的旋转可以有效的避免viewcontrollor判断转向错误的问题

本文介绍了一个iOS应用如何监听设备的方向变化,并根据不同方向执行相应的操作。通过注册设备方向通知,使用NSNotification来实现对设备方向的监听。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

-(void)viewWillAppear:(BOOL)animated{

    UIDevice *device = [UIDevice currentDevice]; //Get the device object
    [device beginGeneratingDeviceOrientationNotifications]; //Tell it to start monitoring the accelerometer for orientation
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; //Get the notification centre for the app
    [nc addObserver:self selector:@selector(orientationChanged:) name:UIDeviceOrientationDidChangeNotification  object:device];
}
-(void)viewWillDisappear:(BOOL)animated {
    
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    UIDevice *device = [UIDevice currentDevice]; //Get the device object
    [nc removeObserver:self name:UIDeviceOrientationDidChangeNotification object:device];
}

- (void)orientationChanged:(NSNotification *)note  {
    UIDeviceOrientation  status= [[UIDevice currentDevice] orientation];
    switch (status) {
        case UIDeviceOrientationPortrait:            // Device oriented vertically, home button on the bottom
            [self dismissViewControllerAnimated:YES completion:nil];
            break;
        case UIDeviceOrientationPortraitUpsideDown:  // Device oriented vertically, home button on the top
            break;
        case UIDeviceOrientationLandscapeLeft:      // Device oriented horizontally, home button on the right
            ;
            break;
        case UIDeviceOrientationLandscapeRight:      // Device oriented horizontally, home button on the left
            
            ;
            break;
        default:
            break;
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值