昨天試過縮放功能,但是在旋轉的時候會出現畫面沒有更新frame而導致 “ landscapeleft / landscape right “
在畫面的右方會出現一大片空白。
這時候我們可以用兩個 instance Methods 來協助解決 “viewWillTransition(to:with:) “
和“ viewWillLayoutSubviews() “
,可以新增並且印出 screen size 。
override func viewWillLayoutSubviews() {
myScrollView.frame = view.frame
print("view will layout -> \(myScrollView.frame.width),\(myScrollView.frame.height) ")
}
override func viewWillTransition(to: CGSize, with:
UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: to, with: with )
print("view will transition -> \(myScrollView.frame.width),\(myScrollView.frame.height)")
}
可以發現,順序是 ::viewWillTransition -> viewWillLayoutSubviews:: 但是 screen size 的更新只出現在 viewWillLayoutSubviews
再配合可以偵測裝置是否有旋轉/翻轉的 propertyvar orientation: UIDeviceOrientation { get }
並且修改 backgroundColor 來提醒我們每次翻轉的不同
switch UIDevice.current.orientation {
case .landscapeLeft :
print ("========== 裝置橫向 左 ========")
myScrollView.frame = view.frame
myScrollView.backgroundColor = UIColor.red
print("view will layout in landScapeLeft-> \(myScrollView.frame.width),\(myScrollView.frame.height) ")
case .landscapeRight :
print ("========== 裝置橫向 右 ========")
myScrollView.frame = view.frame
myScrollView.backgroundColor = UIColor.green
print("view will layout in landscapeRight -> \(myScrollView.frame.width),\(myScrollView.frame.height) ")
case .portrait:
print ("========== portrait ========")
myScrollView.frame = view.frame
myScrollView.backgroundColor = UIColor.yellow
print("view will layout in protrait -> \(myScrollView.frame.width),\(myScrollView.frame.height) ")
default :
print(" others")
}