0

How can I just rotate the buttons when my device is in portrait or landscape mode? I know something like that:

button.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))

But where I have to call it up in my code?
I don't want to set my device in landscape mode, I just want to rotate the icons when it should be in landscape mode.
Thanks in advance!

mafioso
  • 1,630
  • 4
  • 25
  • 45

3 Answers3

1

You should override func

viewWillTransitionToSize(_ size: CGSize, withTransitionCoordinator coordinator:UIViewControllerTransitionCoordinator)

And call transform there

Don't forget to assign CGAffineTransformIdentity when rotated back

More about rotation: https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIContentContainer_Ref/index.html#//apple_ref/occ/intfm/UIContentContainer/viewWillTransitionToSize:withTransitionCoordinator:

Ilya V.
  • 106
  • 6
1

The best way to do this is viewDidLoad add this line of code bellow:

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(rotate), name: UIDeviceOrientationDidChangeNotification, object: nil)

and then in function rotate in case of device orientation do some code like this:

func rotate(){
    if UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation) {
    //your code here in landscape mode
    }
if UIDeviceOrientationIsPortrait(UIDevice.currentDevice().orientation){
    //your code in portrait mode
    }
}

this solution is simple and really easy to do.

PiterPan
  • 1,760
  • 2
  • 22
  • 43
0

I guess you know how to "rotate" the buttons already, so I'll just tell you how to know that the device has rotated.

In a view controller, override willRotateToInterfaceOrientation:

override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {

}

In the method body, you can check the value of toInterfaceOrientation to know which orientation the device is rotating to. For example:

switch toInterfaceOrientation {
    case Portrait:
        // some code here...
    default:
        break
}
Sweeper
  • 213,210
  • 22
  • 193
  • 313