我有一個非常類似的情況。我只有一個視圖控制器,我想要有一個不旋轉的AVCaptureVideoPreviewLayer
。我發現@ SeanLintern88接受的解決方案並不適合我;狀態欄從未移動,我在屏幕上顯示的WKWebView沒有正確調整大小。
我碰到的一個更大的問題是,我在視圖控制器視圖中放入了我的AVCaptureVideoPreviewLayer
。創建一個新的UIView
只是爲了保存圖層要好得多。
之後,我從Apple QA1890: Preventing a View From Rotating發現技術說明。這讓我產生以下SWIFT代碼:
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator)
{
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
coordinator.animateAlongsideTransition(
{ (UIViewControllerTransitionCoordinatorContext) in
let deltaTransform = coordinator.targetTransform()
let deltaAngle = atan2f(Float(deltaTransform.b), Float(deltaTransform.a))
var currentRotation : Float = (self.previewView!.layer.valueForKeyPath("transform.rotation.z")?.floatValue)!
// Adding a small value to the rotation angle forces the animation to occur in a the desired direction, preventing an issue where the view would appear to rotate 2PI radians during a rotation from LandscapeRight -> LandscapeLeft.
currentRotation += -1 * deltaAngle + 0.0001;
self.previewView!.layer.setValue(currentRotation, forKeyPath: "transform.rotation.z")
self.previewView!.layer.frame = self.view.bounds
},
completion:
{ (UIViewControllerTransitionCoordinatorContext) in
// Integralize the transform to undo the extra 0.0001 added to the rotation angle.
var currentTransform : CGAffineTransform = self.previewView!.transform
currentTransform.a = round(currentTransform.a)
currentTransform.b = round(currentTransform.b)
currentTransform.c = round(currentTransform.c)
currentTransform.d = round(currentTransform.d)
self.previewView!.transform = currentTransform
})
}
原來的技術說明中沒有行self.previewView!.layer.frame = self.view.bounds
但我發現很必要的,因爲雖然定位點不動,框架了。沒有這一行,預覽將被抵消。另外,由於我正在做所有的工作,將視圖保持在正確的位置,所以我不得不移除所有的定位約束條件。當我把它們放入時,它們會導致預覽反而在相反的方向上偏移。