簡體   English   中英

設備方向快速變化時如何旋轉按鈕?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM