iPhone旋转操作 | 持续更新

一,当App开启自动旋转时,controller中监测旋转时执行的方法:

    ///旋转处理
    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        
        coordinator.animate { context in
            print(Thread.current.description,context);
            if Thread.current.isMainThread {
                self.recordTableview.reloadData();
            } else {
                DispatchQueue.main.async {
                    self.recordTableview.reloadData();
                }
            }
        } completion: { context in
            print(Thread.current.description);
        }
        print("viewWillTransition");
        super.viewWillTransition(to: size, with: coordinator);
    }
///可通过size.width和size.height判断竖直还是横屏。

之前的方法已经被viewWillTransition方法所代替,所以以下是原来的老方法。

以前的API:
// Notifies when rotation begins, reaches halfway point and ends.
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration API_DEPRECATED("Implement viewWillTransitionToSize:withTransitionCoordinator: instead", ios(2.0, 8.0)) API_UNAVAILABLE(tvos);

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration API_DEPRECATED("Implement viewWillTransitionToSize:withTransitionCoordinator: instead", ios(3.0, 8.0)) API_UNAVAILABLE(tvos);

子View中如果旋转屏幕了,修改其布局:

    override func layoutSubviews() {
        super.layoutSubviews();
        if true == viewOrientation() {
            self.textElem.snp.remakeConstraints { make in
                make.left.equalTo(10.0);
                make.right.equalTo(-10.0);
                make.centerY.equalToSuperview();
                make.height.equalTo(34.0);
            };
        }else{
            self.textElem.snp.remakeConstraints { make in
                make.left.equalTo(10.0);
                make.right.equalTo(-10.0);
                make.centerY.equalToSuperview();
                make.height.equalTo(12.0);
            };
        }
    }

判断当前是否横竖屏的一种方法,当然还有很多方法可以判断,这是通过屏幕去判断,而不是设备的home键去判断:

///屏幕方向,是否是竖直
func viewOrientation() -> Bool {
    
    if #available(iOS 13.0, *) {
        let interfaceOrientation = UIApplication.shared.windows.first?.windowScene?.interfaceOrientation;
        return interfaceOrientation == .portrait ? true : false;
    } else {
        // Fallback on earlier versions
        return UIApplication.shared.statusBarOrientation == .portrait ? true : false;
    };
    
}

Leave a Reply

Required fields are marked *