如何设置相机视图旋转(不使用已弃用的代码)

How to set Camera View rotation (without using deprecated code)

基本上,如何做到这一点:

    - (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    [[(AVCaptureVideoPreviewLayer *)[[self previewView] layer] connection] setVideoOrientation:(AVCaptureVideoOrientation)toInterfaceOrientation];
}

不使用已弃用的代码 (willRotateToInterfaceOrientation)

我的应用需要 iOS9,所以只要新代码向后兼容那么远,我就不需要保留上面的代码。 Apple 建议使用 viewWillTransitionToSize:withTransitionCoordinator: 但我不知道如何使用。

编辑:

我试过了(按照@Matt 的建议)

- (void)viewDidLoad
{
[super viewDidLoad];
override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(
                                           forName: UIApplication.willChangeStatusBarOrientationNotification,
                                           object: nil, queue: nil) { n in
        // this is where you respond
        if let userInfo = n.userInfo {
            // use the userInfo to find out what the new orientation is...
        }
    }
}
}

但它抛出使用未声明的标识符 'override' 错误,因为它在 swift.

除非你试图将 objc 与 swift 混合,否则你需要将 matt 的代码转换为 objc,例如如下所示:

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleDeviceOrientationChange) name:UIApplicationWillChangeStatusBarOrientationNotification object:nil];
}

-(void)handleDeviceOrientationChange:(NSNotification *)notification {
    NSDictionary *userInfo = notification.userInfo;
    // Your code
}

根据 Apple DTS,这段代码完成了同样的事情(我也证实了自己)

- (void) viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
{
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];

    UIDeviceOrientation deviceOrientation = [UIDevice currentDevice].orientation;

    if (UIDeviceOrientationIsPortrait(deviceOrientation) || UIDeviceOrientationIsLandscape(deviceOrientation)) {
        [[(AVCaptureVideoPreviewLayer *)[[self previewView] layer] connection] setVideoOrientation:(AVCaptureVideoOrientation)deviceOrientation];
    }
}