![](/img/trans.png)
[英]View of floating action button not appearing when device orientation changes in swift
[英]How to rotate button when device orientation changes in swift?
當設備處於縱向或橫向模式時,如何旋轉按鈕? 我知道這樣的事情:
button.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
但是我必須在代碼中調用它嗎?
我不想將設備設置為橫向模式,我只想在圖標應處於橫向模式時旋轉圖標。
提前致謝!
最好的方法是在viewDidLoad
添加以下代碼:
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(rotate), name: UIDeviceOrientationDidChangeNotification, object: nil)
然后在面向設備的情況下在函數旋轉中執行以下代碼:
func rotate(){
if UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation) {
//your code here in landscape mode
}
if UIDeviceOrientationIsPortrait(UIDevice.currentDevice().orientation){
//your code in portrait mode
}
}
這個解決方案很簡單,而且確實很容易做到。
您應該覆蓋func
viewWillTransitionToSize(_ size: CGSize, withTransitionCoordinator coordinator:UIViewControllerTransitionCoordinator)
並在那里調用轉換
向后旋轉時不要忘記分配CGAffineTransformIdentity
有關輪播的更多信息: https : //developer.apple.com/library/ios/documentation/UIKit/Reference/UIContentContainer_Ref/index.html#//apple_ref/occ/intfm/UIContentContainer/viewWillTransitionToSize : withTransitionCoordinator :
我想您已經知道如何“旋轉”按鈕了,所以我只告訴您如何知道設備已旋轉。
在視圖控制器中,重寫willRotateToInterfaceOrientation
:
override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
}
在方法主體中,可以檢查toInterfaceOrientation
的值以了解設備將旋轉到哪個方向。 例如:
switch toInterfaceOrientation {
case Portrait:
// some code here...
default:
break
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.