首页 > 解决方案 > Avoid rotation of one view in viewcontroller with orientation change

问题描述

I need to avoid rotation of single view inside the viewcontroller when orientation change. When user change the orientation of the device viewcontroller should be rotated but one view inside that viewcontroller should be kept as itis. Is there a way to achieve this task. I saw many applications use this technique but don't have idea to do this.

Like Adobe Draw App

标签: iosswiftuiviewcontrollerorientation

解决方案


I found the solution for my above question and I state it here because it can be useful for someone.

If you need to keep position as itis of particular view inside the viewcontroller when changing the device orientation we have to rotate that view in inverse direction at the same speed. In iPads rotation duration is 0.4s and in iPhones it will take 0.3s

Example code:

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))

            })
        }
    }
}

推荐阅读