避免在 viewcontroller 中旋转一个视图并改变方向

Avoid rotation of one view in viewcontroller with orientation change

当方向改变时,我需要避免在 viewcontroller 内旋转单个视图。当用户更改设备的方向时,viewcontroller 应该旋转,但 viewcontroller 内部的一个视图应该保持原样。有没有办法完成这个任务。我看到很多应用程序都使用这种技术,但不知道要这样做。

喜欢Adobe Draw App

我找到了上述问题的解决方案,并在此说明,因为它可能对某些人有用。

如果您需要在更改设备方向时将特定 view 的位置保持在 viewcontroller 内,我们必须以相同的速度沿相反方向旋转该视图。在 iPad 中旋转持续时间为 0.4s,在 iPhone 中需要 0.3s

示例代码:

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {

    var timeDuration: TimeInterval = 0.4 //for iPads
    if DeviceHardware.deviceIsPhone() {
        timeDuration = 0.3 //for iPhones
    }

    if UIDevice.current.orientation.isLandscape {

        if UIDevice.current.orientation == .landscapeLeft{
            UIView.animate(withDuration: timeDuration, animations: {
                let degrees : Double = 0; //the value in degrees
                self.relevantView!.transform = CGAffineTransform(rotationAngle: CGFloat(degrees * .pi/180))

            })
        }else{
            UIView.animate(withDuration: timeDuration, animations: {
                let degrees : Double = 180; //the value in degrees
                self.relevantView!.transform = CGAffineTransform(rotationAngle: CGFloat(degrees * .pi/180))

            })
        }

    } else {

        if UIDevice.current.orientation == .portraitUpsideDown{
            UIView.animate(withDuration: timeDuration, animations: {
                let degrees : Double = -90; //the value in degrees
                self.relevantView!.transform = CGAffineTransform(rotationAngle: CGFloat(degrees * .pi/180))

            })
        }else{
            UIView.animate(withDuration: timeDuration, animations: {
                let degrees : Double = 90; //the value in degrees
                self.relevantView!.transform = CGAffineTransform(rotationAngle: CGFloat(degrees * .pi/180))

            })
        }
    }
}

您只需要对视图应用反向动画旋转即可取消系统旋转:

重写 func viewWillTransition(大小:CGSize,协调器:UIViewControllerTransitionCoordinator){

coordinator.animate(alongsideTransition: { (context) in
    
    self.nonRotatingView!.transform = self.nonRotatingView!.transform.concatenating(context.targetTransform.inverted())
    
    
}) { (context) in
 
    // Something to do on completion ?
    
}

}