iPhoneX状态条的隐藏与显示

此文写于iPhoneX上市前,里面的代码未经真机测试,只在模拟器测试过!!!!!!!

继iPhoneX和我的刘海同款之尴尬后,我遇到了iPhoneX横屏下状态条无法显示之尴尬。终于,给我显示出来了:
iPhoneX状态条的隐藏与显示_第1张图片
原因是需要实现-(void)setNeedsStatusBarAppearanceUpdate这个方法。
不信你看,当你点击-(BOOL)prefersStatusBarHidden这个方法看它的quick help:
iPhoneX状态条的隐藏与显示_第2张图片
具体代码如下:

#import "ViewController.h"

@interface ViewController ()

@property BOOL isStatusBarHidden;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _isStatusBarHidden = NO;
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
    [button setBackgroundColor:[UIColor grayColor]];
    [button setTitle:@"button" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

-(void)buttonClicked: sender {
    _isStatusBarHidden = !_isStatusBarHidden;
    UIDeviceOrientation *orientation = [UIDevice currentDevice].orientation;
    if (orientation == UIDeviceOrientationPortrait) {
        NSLog(@"Portrait");
        [super setNeedsStatusBarAppearanceUpdate];
    }else {
        NSLog(@"Landscape");
        [self setNeedsStatusBarAppearanceUpdate];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)setNeedsStatusBarAppearanceUpdate {
    NSLog(@"---self setNeedsStatusBarAppearanceUpdate---");
}

-(BOOL)prefersStatusBarHidden {
    return _isStatusBarHidden;
}

@end

不过这个方法有个弊端,就是状态条的属性(显示与否、字体颜色等)只能在竖屏情况进行设置更换,横屏下的状态条只能维持竖屏下的状态条的样子。从这个demo上直观看的效果就是:竖屏下点击button更换状态条状态,横屏下状态条维持竖屏状态条状态,横屏下点击button更换状态条状态无效。

也许会问,为什么要[self setNeedsStatusBarAppearanceUpdate];,那是因为iPhoneX里的setNeedsStatusBarAppearanceUpdate方法横屏无效!!!我的天,所以只能重写。。。但是这个方法是不公开的。。。于是只能这样很挫很挫的半实现这个效果。如果你有更好的方法,望告知!

你可能感兴趣的:(objective-c)