viewWillLayoutSubviews和通知的使用机制

做横竖屏最重要的是确定横竖屏响应的接口。目前我知道的有两种方式 :

1.使用通知。

  • (void)viewDidLoad
    {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_orientationDidChange:) name:UIDeviceOrientationDidChangeNotification object:nil];

}

  • (void)dealloc {

    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil];
    }

-(void)_orientationDidChange:(NSNotification*)notify
{
[self _shouldRotateToOrientation:(UIDeviceOrientation)[UIApplication sharedApplication].statusBarOrientation];
}

-(void)_shouldRotateToOrientation:(UIDeviceOrientation)orientation {
if (orientation == UIDeviceOrientationPortrait ||orientation == UIDeviceOrientationPortraitUpsideDown) {
// 竖屏
}else {
// 横屏
}
}
上述代码,一看就明白。
2.使用 viewWillLayoutSubviews
测试发现横竖屏切换的时候,系统会响应一些函数,其中 viewWillLayoutSubviews就是之一。

  • (void)viewWillLayoutSubviews
    {
    [self _shouldRotateToOrientation:(UIDeviceOrientation)[UIApplication sharedApplication].statusBarOrientation];
    }
    通过上述一个函数就知道横竖屏切换的接口了。
    注意:
    viewWillLayoutSubviews只能用在ViewController里面,在view里面没有响应。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容